在 swift 中以编程方式清除 NSView

Clear NSView programmatically in swift

我有一个 NSView 连接到自定义 class。
那个视图上有一些绘图:

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()