目前,这是我的代码:
import UIKit
class ViewController: UIViewController {
var dx : CGFloat = 0
var dy : CGFloat = 0
@IBOutlet var sprite: UIImageView!
@IBAction func A(sender: AnyObject) {
dx = -1;
}
@IBAction func W(sender: AnyObject) {
dy = -1;
}
@IBAction func D(sender: AnyObject) {
dx = 1;
}
@IBAction func S(sender: AnyObject) {
dy = 1;
}
override func viewDidLoad() {
super.viewDidLoad()
backgroundThread(delay: 10
, background: {
while(true){
self.sprite.frame.origin.x += self.dx;
self.sprite.frame.origin.x += self.dy;
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
这是backgroundThread函数(它确实有效。我用简单的println()测试过):
func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
if(background != nil){ background!(); }
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
if(completion != nil){ completion!(); }
}
}
}
出于某种原因,当我按下任何按钮时,它不会开始移动。有没有人有任何建议?