gpt4 book ai didi

ios - 如何同时对多个对象应用动态行为

转载 作者:搜寻专家 更新时间:2023-11-01 07:18:22 26 4
gpt4 key购买 nike

我正在尝试对刚刚从数组创建的 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)


}
}

}

最佳答案

我修改了您的一些代码行,它非常适合我。

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

截图:

enter image description here

关于ios - 如何同时对多个对象应用动态行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40581923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com