当我启动我的应用程序时,我看到UILabel掉下来,然后我将它移动到它并保持在那里。 为什么不下降? 如何在移动元素之后使GravityBehavior?
class ViewController: UIViewController
{
var helloWorldLabel: UILabel!
var panGestureRecognizer: UIPanGestureRecognizer!
var animator: UIDynamicAnimator!
override func viewDidLoad()
{
super.viewDidLoad()
var str:NSString = "Hello World"
let labelFrame = CGRect(x: 0, y: 0, width:200, height: 100);
helloWorldLabel = UILabel(frame: labelFrame)
helloWorldLabel.userInteractionEnabled = true
helloWorldLabel.text = str as String
helloWorldLabel.frame = labelFrame;
helloWorldLabel.backgroundColor = UIColor.grayColor()
helloWorldLabel.center = view.center
view.addSubview(helloWorldLabel)
panGestureRecognizer = UIPanGestureRecognizer(target: self,action: "handlePanGestures:")
helloWorldLabel.addGestureRecognizer(panGestureRecognizer)
animator = UIDynamicAnimator(referenceView: view)
let collisionBehavior = UICollisionBehavior(items: [helloWorldLabel])
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collisionBehavior)
let gravityBehavior = UIGravityBehavior(items: [helloWorldLabel])
animator.addBehavior(gravityBehavior)
}
func handlePanGestures(sender: UIPanGestureRecognizer)
{
if sender.state != .Ended && sender.state != .Failed
{
let location = sender.locationInView(sender.view!.superview!)
sender.view!.center = location
}
}
}
答案 0 :(得分:0)
你所做的一切都是正确的,你必须改变的是一旦消化状态结束,你必须再次添加重力行为。我修改的代码如下所示
class JsonParser: UIViewController {
var animator: UIDynamicAnimator!
var helloWorldLabel: UILabel!
var panGestureRecognizer: UIPanGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
let str:NSString = "Hello World"
let labelFrame = CGRect(x: 0, y: 0, width:200, height: 100);
helloWorldLabel = UILabel(frame: labelFrame)
helloWorldLabel.userInteractionEnabled = true
helloWorldLabel.text = str as String
helloWorldLabel.frame = labelFrame;
helloWorldLabel.backgroundColor = UIColor.grayColor()
helloWorldLabel.center = view.center
view.addSubview(helloWorldLabel)
panGestureRecognizer = UIPanGestureRecognizer(target: self,action: "handlePanGestures:")
helloWorldLabel.addGestureRecognizer(panGestureRecognizer)
animator = UIDynamicAnimator(referenceView: view)
AddCollisionAndGravity()
func AddCollisionAndGravity () {
animator.removeAllBehaviors()
let collisionBehavior = UICollisionBehavior(items: [helloWorldLabel])
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collisionBehavior)
let gravityBehavior = UIGravityBehavior(items: [helloWorldLabel])
animator.addBehavior(gravityBehavior)
}
func handlePanGestures(sender: UIPanGestureRecognizer)
{
if sender.state != .Ended && sender.state != .Failed
{
let location = sender.locationInView(sender.view!.superview!)
sender.view!.center = location
}else if sender.state == UIGestureRecognizerState.Ended{
AddCollisionAndGravity()
}
}
上述代码将满足您的期望。最佳做法是在添加新动画之前从动画师 animator.removeAllBehaviors()中移除以前的行为。我希望这对您有所帮助。