繁体   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