![](/img/trans.png)
[英]Lazy instantiating a UIDynamicAnimator with referenceView - Swift
[英]UIDynamicAnimator dropping balls loop in swift 3
我有UIDynamicAnimator
,球從上到下掉落,但有時掉3個球,有時掉5個……等等。
但是我在for循環中添加to = 50
必須掉落50球
錯誤在哪里?
我的代碼在下面。
class ViewController: UIViewController {
var squareView: UIView!
var numberlet: UILabel!
var gravity: UIGravityBehavior!
var animator: UIDynamicAnimator!
var collision: UICollisionBehavior!
var itemBehaviour: UIDynamicItemBehavior!
override func viewDidLoad() {
super.viewDidLoad()
let from = 0
let to = 50
let by = 1
for i in stride(from: from, to: to, by: by) {
let number = randomInt(min: 12, max:99)
let color = randomInt(min: 1, max:5)
let seconds = 3 * i
delayWithSeconds(Double(seconds)) {
self.start( color : "\(color)", number: "\(number)")
}
}
}
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
override func loadView() {
super.loadView()
view.backgroundColor = UIColor.white
}
func start(color : String, number : String){
squareView = UIView(frame: CGRect(x: view.frame.size.width/2 - 30, y: 0, width: 70, height: 70))
squareView.layer.cornerRadius = 0
squareView.backgroundColor = UIColor(patternImage: UIImage(named: "\(color).png")!)
view.addSubview(squareView)
numberlet = UILabel(frame:CGRect(x: squareView.frame.size.width/2 - 18 , y: 0 , width: 70, height: 70))
numberlet.textColor = UIColor.black
numberlet.font = UIFont.init(name: "Helvetica-Bold", size: 30)
numberlet.text = number
squareView.addSubview(numberlet)
animator = UIDynamicAnimator(referenceView: view)
gravity = UIGravityBehavior(items: [squareView])
animator.addBehavior(gravity)
collision = UICollisionBehavior(items: [squareView])
collision.translatesReferenceBoundsIntoBoundary = true
// collision.addBoundaryWithIdentifier("barrier", fromPoint: CGPointMake(self.view.frame.origin.x, 350), toPoint: CGPointMake(self.view.frame.origin.x + self.view.frame.width, 350))
animator.addBehavior(collision)
itemBehaviour = UIDynamicItemBehavior(items: [squareView])
itemBehaviour.elasticity = 0.3
animator.addBehavior(itemBehaviour)
delayWithSeconds(2.9) {
self.squareView.removeFromSuperview()
self.numberlet.removeFromSuperview()
}
}
func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我實現了您的代碼。 您問題的原因似乎在這里:
let seconds = 3 * i
delayWithSeconds(Double(seconds))
self.start( color : "\(color)", number: "\(number)")
在聲明3 * i的位置,您要增加丟棄下一個的時間,因此要丟棄的seconds
變為0-3秒,0-6秒,0-9秒,0-12秒,依此類推。 因此,並不是說您沒有丟下新方塊,而是每次刪除下一個方塊所花費的時間增加了3秒。
如果這是預期的行為,那么我不確定您的問題是什么。 您的代碼正在我的設備上運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.