Clear NSView programmatically in swift

99封情书 提交于 2019-12-07 19:49:46

问题


I have a NSView connected to a custom class.
There's some drawing on that view:

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

And now I need to write a function to completely clear that view.


回答1:


Not too sure what you mean by completely clear that view but can't you just fill it with a solid colour?

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

(Not up to speed with the Swift hotness yet)

update I improving my Swift chops behold!

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



回答2:


Something like this should suffice. I used something like this in my project to clear NSView.

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



回答3:


Swift 4.2 solution:

myView.subviews.removeAll()


来源:https://stackoverflow.com/questions/28248467/clear-nsview-programmatically-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!