drawRect不会更新显示

时间:2016-12-14 02:16:09

标签: swift

有几个关于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似乎不再被调用

1 个答案:

答案 0 :(得分:1)

如果要在Storyboard中创建drawExamples实例,则必须覆盖

init?(coder aDecoder: NSCoder)

awakeFromNib()

而不是

override init(frame: CGRect)

制作计时器。我更喜欢awakeFromNib。

所以代码如下所示。

class drawExamples: UIView {
    var shapePosX : CGFloat = 0
    var shapePosY : CGFloat = 0

    override func awakeFromNib() {
        var time1 = NSTimer.scheduledTimerWithTimeInterval(
            1,
            target: self,
            selector: #selector(update),
            userInfo: nil,
            repeats: true)
    }

    func update() {
        shapePosX = shapePosX + 1
        shapePosY = shapePosY + 1
        self.setNeedsDisplay()
    }