2016-09-29 115 views
1

我在Swift 3.0中編寫了這段代碼,但draw方法不是從func drawBorder調用的needsDisplay = true;通過在另一個視圖中單擊按鈕調用drawBorder。 感謝您的任何提示。func draw(_ dirtyRect:NSRect)不叫

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 
} 

}

回答

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 
} 
} 

通知從視圖控制器postec這樣

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

嘗試調用你的看法setNeedsDisplay(_:)方法,這應該叫draw(_:)方法。千萬不要自己撥打draw(_:)方法。

+0

而是在drawBorder方法needsDisplay財產嘗試調用setNeedsDisplay()的。 –

+0

我不叫draw(_ :)我只是設置needsDisplay = true,它應該確保調用draw(_ :)。我懷疑這是因爲我通過在自定義視圖外點擊按鈕來調用drawBorder。如果我從**覆蓋func mouseUp(事件:NSEvent)調用它{ drawBorder() } **,那麼它可以很好地工作。 – Dawy

+0

我增加了setNeedsDisplay(self.bounds)並且沒有改變。請注意,setNeedsDisplay(InvalidRect:NSRect)需要參數Swift 3 – Dawy