2016-11-15 51 views
-1

对你来说可能是一件容易的事。如何正确使用CollisionBehavior使物品相互碰撞

我只是想用正确的方式使用collisionMode。我的代码似乎没问题(没有错误),但项目只与视图的边界相冲突。不与对方。

我想知道“translatesReferenceBoundsIntoBoundary”是否会覆盖collisionMode。

也许我应该使用“addBoundary(withIdentifier:NSCopying,from:CGPoint,to:CGPoint)”方法而不是“translateReferenceBoundsIntoBoundary”,但没有找到如何实现NSCopying类。

下面我的代码细节。

在此先感谢。

import UIKit 

class ViewController: UIViewController { 

var tests:[String] = ["test1","test2","test3","test4","test5","test6","test7","test8","test9","test10","test11"] 

var label:UILabel! 
var color:UIColor! 

var dynamicBehavior:UIDynamicBehavior! 
var collisionBehavior:UICollisionBehavior! 

var animatorArray = [UIDynamicAnimator]() 


var countLabel = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let size:CGFloat = 50.0 
    var positionX:CGFloat = 60.0 
    var positionY:CGFloat = 100.0 


    for test in tests { 
    label = UILabel(frame:CGRect(x: positionX, y: positionY, width: size, height: size)) 
    label.center = CGPoint(x: positionX, y: positionY) 
    label.layer.cornerRadius = size * 0.5 
    label.layer.masksToBounds = true 
    label.backgroundColor = color 
    label.textAlignment = .center 
    label.textColor = UIColor.white 
    label.adjustsFontSizeToFitWidth = true 
    label.numberOfLines = 1 
    label.text = test 
    self.view.addSubview(label) 
    countLabel = countLabel + 1 

     if countLabel == 4 || countLabel == 8 { 
      positionX = positionX - 140 
      positionY = positionY + 100 } 
     else { positionX = positionX + 60} 

    for (i,_) in tests.enumerated() { 

     let gravity = UIGravityBehavior(items: [label]) 
     let direction = CGVector(dx: 0.0, dy: 1.0) 
     gravity.gravityDirection = direction 

     let bounce = UIDynamicItemBehavior(items: [label]) 
     bounce.elasticity = 1.0 

     let collisions = UICollisionBehavior(items: [label]) 
     collisions.translatesReferenceBoundsIntoBoundary = true 
     collisions.collisionMode = UICollisionBehaviorMode.everything 

    animatorArray.append(UIDynamicAnimator(referenceView: self.view)) 
    animatorArray[i].addBehavior(bounce) 
    animatorArray[i].addBehavior(collisions) 
    animatorArray[i].addBehavior(gravity) 
    } 
} 

} 
} 
+0

伙计。 NSCopying只是一个字符串。 'coll.addBoundary(withIdentifier:“bottom”as NSString,from:p1,to:p2)' – matt

+0

谢谢matt。是的,的确很简单。我正在寻找很远。 – Bastien

+0

没问题!而且我看到keithbhunter已经正确回答了你的实际问题,所以你应该很好走。 (你应该接受他的回答:他完全正确的构建你的循环。) – matt

回答

1

您的每一个标签被添加到UIDynamicAnimator所有的行为单独实例一个单独的实例在for循环。您只能制作动画师的一个属性和每个行为,并将每个标签添加到相同的动画师和行为中。这样,动画师负责所有的标签,而不仅仅是一个。

+0

我明白你的意思是keithbhunter。我会试着弄清楚如何去做。 (我是面向对象编程的新手)。谢谢你的建议。 – Bastien