Bastien Bastien - 19 days ago 9
Swift Question

How to apply dynamicBehavior on multiple objects simultaneously

I'm trying to use DynamicBehaviors on Label objects I have just created from a Array. For this I use the "For In" loop. All objects get created as expected, but only the last get dynamic.

Maybe I should use the UIDynamicItemGroup, but after many tries, I still don't figure out how to use it.

As you are maybe wondering, I'm new to object oriented programming so I hope it will not be a waste of time for you.

Below the code I have actually.

Thanks in advance.

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)


}
}

}

Answer

I modified some line of your code and it's perfectly working for me.

Thanks to Alexander Momchliov

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)
}

Screenshot:

enter image description here

Comments