UIDynamicAnimator在swift 3中丢球循环
Posted
技术标签:
【中文标题】UIDynamicAnimator在swift 3中丢球循环【英文标题】:UIDynamicAnimator dropping balls loop in swift 3 【发布时间】:2017-03-11 18:43:21 【问题描述】:我有UIDynamicAnimator
,球从上到下掉下来,但有时掉 3 个球,有时掉 5 个......等等。
但我在我的 for 循环中添加了 to = 50
必须是 drop 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.
【问题讨论】:
问题已编辑并清除。 @matt 我清除了我的问题。 【参考方案1】:我实现了你的代码。您的问题的原因似乎在于这里:
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 秒。
如果这是预期的行为,那么我不确定您的问题是什么。您的代码正在我的设备上运行。
【讨论】:
以上是关于UIDynamicAnimator在swift 3中丢球循环的主要内容,如果未能解决你的问题,请参考以下文章
使用 UIDynamicAnimator 水平动画 UIView