对你来说可能很容易。
我只是想以正确的方式使用collisionMode。我的代码似乎没问题(没有bug),但是项目只与视图的边界冲突。没有彼此。
我想知道“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 :(得分:1)
每个标签都被添加到UIDynamicAnimator
的单独实例中,其中包含for循环中所有行为的单独实例。您只需制作动画师的一个属性和每个行为,并将每个标签添加到相同的动画师和行为中。通过这种方式,动画师负责所有标签,而不仅仅是一个标签。