不调用func draw(_ dirtyRect:NSRect)

时间:2016-09-29 18:52:30

标签: draw swift3 nsview

我在Swift 3.0中编写了这段代码,但是没有通过needsDisplay = true从func drawBorder调用draw方法;通过单击另一个视图中的按钮来调用drawBorder。 谢谢你的提示。

class clsDrawView: NSView {

    private var redraw = false
    var border = NSBezierPath()
    var color = NSColor()

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
        if redraw {
            color.setStroke()
            border.stroke()
        }
    }

    func drawBorder() {
        redraw = true
        color = NSColor.blue
        border.lineWidth = CGFloat(10)
        border.move(to: NSPoint(x: 20, y: 20))
        border.line(to: NSPoint(x: 50, y: 50))

        needsDisplay = true
    }
}

2 个答案:

答案 0 :(得分:1)

尝试在您的视图中调用setNeedsDisplay(_:)方法,这应该调用draw(_:)方法。永远不要自己打电话给draw(_:)方法。

答案 1 :(得分:1)

最后我通过通知

解决了这个问题
class clsDrawView: NSView {

private var draw = false
private var border = NSBezierPath()
var color = NSColor()

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    NotificationCenter.default.addObserver(self, selector: #selector(self.drawBorder(_:)), name: NSNotification.Name(rawValue: "drawBorder"), object: nil)

    // Drawing code here.
    if draw {
        color.setStroke()
        border.stroke()
    }
}

func drawBorder(_ notification: NSNotification) {
    draw = true
    color = NSColor.black
    NSBezierPath.setDefaultLineWidth(4)
    border.lineWidth = CGFloat(10)
    border = NSBezierPath(rect: self.bounds)
    needsDisplay = true
}   
}

通知是来自ViewController的postec,就像这样

@IBAction func btnDraw(_ sender: NSButton) {
    NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "drawBorder"), object: sender)
}