我想在for循环中移动一个矩形来创建随机游走。但我只能在最终位置之间不动。我需要做些什么才能看到各个步骤?
import UIKit
import PlaygroundSupport
class ViewController:UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
}
}
class bird: UIView {
var x:CGFloat
var y:CGFloat
override init(frame: CGRect){
self.x=0
self.y=0
super.init(frame: frame)
}
func stepit(dx: CGFloat, dy: CGFloat ){
self.frame.origin.x += dx
self.frame.origin.y += dy
}
override func draw(_ rect: CGRect) {
self.backgroundColor = #colorLiteral(red: 0.960784316062927, green: 0.705882370471954, blue: 0.200000002980232, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
PlaygroundPage.current.needsIndefiniteExecution = true
let b=bird(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
viewController.view.addSubview(b)
for i in i... 100 {
b.stepit(dx: CGFloat(arc4random_uniform(10)), dy: CGFloat(arc4random_uniform(10) ))
}
答案 0 :(得分:1)
您应该使用animateWithDuration()
。将以下代码放在stepit()
函数中。正如holex所说,请对该语言进行一些研究。 for循环不会在每一步都暂停,你正在移动鸟,但是你只是看到了结束点,因为它如此快地击中了for循环。
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
self.frame.origin.x = dx
self.frame.origin.y = dy
}, completion: { (finished: Bool) -> Void in
})
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/