【发布时间】:2016-11-15 12:43:27
【问题描述】:
对你来说可能很容易。
我只是想以正确的方式使用碰撞模式。我的代码似乎没问题(没有错误),但项目只与视图的边界发生冲突。不是彼此。
我想知道“translatesReferenceBoundsIntoBoundary”是否会覆盖碰撞模式。
也许我应该使用“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)
}
}
}
}
【问题讨论】:
-
老兄。 NSCopying 只是一个字符串。
coll.addBoundary(withIdentifier: "bottom" as NSString, from:p1, to:p2) -
谢谢马特。是的,确实很容易。我一直在寻找。
-
没问题!我看到 keithbhunter 已经正确回答了你的实际问题,所以你应该很高兴。 (你应该接受他的回答:他对你的循环的构造是完全正确的。)
标签: ios arrays swift3 collision