關於drawRect有幾個問題都幫助我,但仍然無法讓我的代碼正常工作。drawRect不會更新顯示
我有一個簡單的類,drawExamples:
class drawExamples: UIView {
var shapePosX : CGFloat = 0
var shapePosY : CGFloat = 0
override init(frame: CGRect) {
super.init(frame: frame)
var time1 = NSTimer.scheduledTimerWithTimeInterval(
1,
target: self,
selector: #selector(update),
userInfo: nil,
repeats: true)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func update() {
shapePosX = shapePosX + 1
shapePosY = shapePosY + 1
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 3.0)
CGContextSetStrokeColorWithColor(context, UIColor.purpleColor().CGColor)
CGContextMoveToPoint(context, shapePosX, shapePosY)
CGContextAddLineToPoint(context, shapePosX + 250, shapePosY + 320)
CGContextAddLineToPoint(context, shapePosX + 300, shapePosY + 320)
CGContextSetFillColorWithColor(context,UIColor.purpleColor().CGColor)
CGContextFillPath(context)
}
}
它最初吸引的觀點,但它永遠不會更新。更新功能運行正常,形狀位置更新正常。我假設setNeedsDisplay的作品,我只是不知道爲什麼drawRect不會重繪我設置的形狀。 drawRect中似乎並沒有得到初始運行
看起來好像你已經爲視圖指定了框架或設置了任何約束,所以它的高度和寬度都爲零。 – par
這是你使用代碼做的事嗎?或者它是對約束引腳事物的設置?這是否意味着自定義類應該是默認的SKView,如果是這樣,爲什麼我不必設置這些約束來獲取自定義類爲drawExamples時顯示的形狀?對於這些問題感到抱歉,新的迅速,並有一個粗略的時間瞭解所有的部分,使它們一起工作 – Dal
自動佈局不一定是問題在這裏。 (對不起@dal)它可能會更深一點 - 你爲什麼使用drawRect()來「移動」你的UIView? drawRect()通常用於圖層繪製,而自動佈局約束用於移動UIViews - 通常是超級視圖中的子視圖。所以我的問題是:你想用這種觀點做什麼?它是另一個子視圖嗎?它是一個CAShapeLayer嗎? – dfd