我正在用Swift构建一个应用程序。我编写了一个UIGravityBehavior,一个拖放函数,以及3个按钮和地板UIImageView之间的碰撞检测,但是当按下其中一个按钮时,该按钮的UIGravityBehavior就不再存在了。帮个忙就好了。
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)
}发布于 2015-12-18 18:39:54
您应该添加一个附件属性,就像处理其他行为一样。例如:
var attachment: UIAttachmentBehavior?在touchesBegan中,将Ball1.center = location替换为
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替换为
if attachment != nil
{
attachment!.anchorPoint = location
}然后实现touchesEnded
if animator != nil && attachment != nil
{
animator.removeBehavior(self.attachment!)
self.attachment = nil
}我将添加您编写的代码,这将始终使Ball1遵循用户的触摸。不知道你是不是打算这么做。
https://stackoverflow.com/questions/34360738
复制相似问题