簡體   English   中英

以編程方式快速清除NSView

[英]Clear NSView programmatically in swift

我有一個NSView連接到自定義類。
該視圖上有一些圖形:

class LineDrawer: NSView {
    var linear = NSBezierPath()
    var storage = NSUserDefaults.standardUserDefaults()

    override func drawRect(dirtyRect: NSRect) {
        var color = NSColor()

        if let newLoadedData = storage.objectForKey("color") as? NSData {
            if let currentColor = NSUnarchiver.unarchiveObjectWithData(newLoadedData) as? NSColor {
                color = currentColor
            }
        }

        color.set()
        linear.lineWidth = CGFloat(storage.integerForKey("width"))
        linear.stroke()
    }

    override func mouseDown(theEvent: NSEvent) {
        super.mouseDown(theEvent)
        let location = theEvent.locationInWindow
        var lastPt = theEvent.locationInWindow
        lastPt.y -= frame.origin.y
        linear.moveToPoint(lastPt)
    }

    override func mouseDragged(theEvent: NSEvent) {
        super.mouseDragged(theEvent)
        var newPt = theEvent.locationInWindow
        newPt.y -= frame.origin.y
        linear.lineToPoint(newPt)
        needsDisplay = true
    }
}

現在,我需要編寫一個函數來完全清除該視圖。

不太清楚完全清除該視圖的意思是什么,但是不能僅用單色填充它嗎?

[[NSColor windowBackgroundColor] setFill];
NSRectFill(self.bounds);

(尚未趕上Swift的熱度)

更新我改善了我的Swift排骨!

NSColor.windowBackgroundColor().setFill()
NSRectFill(self.bounds)

這樣的東西就足夠了。 我在項目中使用了類似的方法來清除NSView。

while curView.subviews.count > 0 {
   curView.subviews.last?.removeFromSuperview()
}

Swift 4.2解決方案:

myView.subviews.removeAll()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM