您需要在drawRect
通话之外启动计时器;didMoveToSuperview
可能是一个好地方,但这取决于您要完成的工作。然后,在 中timerRedraw
,调用setNeedsDisplay()
以触发重新绘制。
var timer: NSTimer?
override func didMoveToSuperview() {
// Stop the timer if it was already running
if timer != nil {
timer.invalidate()
timer = nil
}
// Only start the timer if the view is actually part of a view hierarchy
if superview != nil {
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "timerRedraw", userInfo: nil, repeats: true)
}
}
func timerRedraw() {
x += 5
y += 6
setNeedsDisplay()
}
我强烈推荐阅读 Apple 的iOS 绘图和打印指南,它解释了开始在 iOS 中进行自定义绘图所需了解的所有内容。