首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拖拽函数快速生成问题

拖拽函数快速生成问题
EN

Stack Overflow用户
提问于 2015-12-18 17:18:08
回答 1查看 169关注 0票数 1

我正在用Swift构建一个应用程序。我编写了一个UIGravityBehavior,一个拖放函数,以及3个按钮和地板UIImageView之间的碰撞检测,但是当按下其中一个按钮时,该按钮的UIGravityBehavior就不再存在了。帮个忙就好了。

代码语言:javascript
复制
import UIKit

class ViewController: UIViewController {

var location = CGPoint(x: 0, y: 0)
var animator:  UIDynamicAnimator?
var gravity: UIGravityBehavior?
var isRotating = false
var collision: UICollisionBehavior!
@IBOutlet var Ball1: UIButton!

@IBOutlet var Ball2: UIButton!

@IBOutlet var Ball3: UIButton!

@IBOutlet var Floor: UIImageView!

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let touch = touches.first as UITouch!

    location = touch.locationInView(self.view)

    Ball1.center = location
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let touch = touches.first as UITouch!
    location = touch.locationInView(self.view)

    Ball1.center = location
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.animator = UIDynamicAnimator(referenceView: self.view)

    let gravity = UIGravityBehavior (items: [self.Ball1!, self.Ball2!, self.Ball3!])
    let direction = CGVectorMake(0.0, 1.0)
    gravity.gravityDirection = direction
    self.animator?.addBehavior(gravity)

    collision = UICollisionBehavior(items: [ Ball1!, Ball2!, Ball3!])
    collision.translatesReferenceBoundsIntoBoundary = true
     collision.addBoundaryWithIdentifier("Floor", fromPoint: CGPointMake(self.view.frame.origin.x, -7), toPoint: CGPointMake(self.view.frame.origin.x + self.view.frame.width, -7))
    animator!.addBehavior(collision)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-18 18:39:54

您应该添加一个附件属性,就像处理其他行为一样。例如:

代码语言:javascript
复制
var attachment: UIAttachmentBehavior?

在touchesBegan中,将Ball1.center = location替换为

代码语言:javascript
复制
if CGRectContainsPoint(Ball1.frame,location)
{
    attachment = UIAttachmentBehavior(item: Ball1, attachedToAnchor: location)
    animator!.addBehavior(attachment!)
}
if CGRectContainsPoint(Ball2.frame,location)
{
    attachment = UIAttachmentBehavior(item: Ball2, attachedToAnchor: location)
    animator!.addBehavior(attachment!)
}
if CGRectContainsPoint(Ball3.frame,location)
{
    attachment = UIAttachmentBehavior(item: Ball3, attachedToAnchor: location)
    animator!.addBehavior(attachment!)
}

然后在touchesMoved中将Ball1.center = location替换为

代码语言:javascript
复制
if attachment != nil
{
    attachment!.anchorPoint = location
}

然后实现touchesEnded

代码语言:javascript
复制
if animator != nil && attachment != nil
{
    animator.removeBehavior(self.attachment!)
    self.attachment = nil
}

我将添加您编写的代码,这将始终使Ball1遵循用户的触摸。不知道你是不是打算这么做。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34360738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档