2

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.

Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
pomo_mondreganto
  • 2,028
  • 2
  • 28
  • 56

3 Answers3

2

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)
Daniel Farrell
  • 9,316
  • 8
  • 39
  • 62
  • Thanks, I was looking for a way to remove drawing, but this will be good too. – pomo_mondreganto Jan 31 '15 at 13:29
  • Yes, you can't remove drawing once it is applied. An alternative is to set a flag on your classes which turns specific drawing on or off and tell the the view to `setNeedsDisplay:YES`. On the next pass through the view will be blank and if no additional drawing is required none will be done. This is more efficient than doing the drawing every time then erasing it with the rect fill. – Daniel Farrell Jan 31 '15 at 16:02
0

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()
}
XueYu
  • 2,355
  • 29
  • 33
0

Swift 4.2 solution:

myView.subviews.removeAll()
ixany
  • 5,433
  • 9
  • 41
  • 65