我试图在我刚从Array创建的Label对象上使用DynamicBehaviors。为此,我使用" For In"环。所有对象都按预期创建,但只有最后一个获得动态。
也许我应该使用UIDynamicItemGroup,但经过多次尝试后,我仍然没有弄清楚如何使用它。
你可能想知道,我是面向对象编程的新手,所以我希望你不会浪费时间。
我实际上在代码下面。
提前致谢。
import UIKit
class ViewController: UIViewController {
var tests:[String] = ["test1","test2","test3","test4","test5","test6","test7","test8","test9","test10","test11"]
var viewLabelArray:UIView!
var label:UILabel!
var color:UIColor!
var animator:UIDynamicAnimator!
var dynamicBehavior:UIDynamicBehavior!
var collisionBehavior:UICollisionBehavior!
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
}
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
let boundries = UICollisionBehavior(items: [label])
boundries.translatesReferenceBoundsIntoBoundary = true
animator = UIDynamicAnimator(referenceView: self.view)
animator.addBehavior(bounce)
animator.addBehavior(boundries)
animator.addBehavior(gravity)
}
}
}
答案 0 :(得分:2)
我修改了一些代码,它完全适合我。
var animatorArray = [UIDynamicAnimator]()
for (i,test) in tests.enumerated() {
//code
let bounce = UIDynamicItemBehavior(items: [label])
bounce.elasticity = 1
let boundries = UICollisionBehavior(items: [label])
boundries.translatesReferenceBoundsIntoBoundary = true
animatorArray.append(UIDynamicAnimator(referenceView: self.view))
animatorArray[i].addBehavior(gravity)
animatorArray[i].addBehavior(bounce)
animatorArray[i].addBehavior(boundries)
}
<强>截图:强>