So in my Swift OS X app I have one custom view and one button. When I start my app, my view shows a red oval and I need to change that drawing to drawRectangle()-method when i click my button.
My custom view's class MyView looks like following:
import Cocoa
import AppKit
class MyView: NSView {
var isTrue = true
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
if isTrue {
DrawingMethods.drawOval()
} else {
DrawingMethods.drawRectangle()
}
}
@IBAction func buttonPressed(sender: AnyObject) {
isTrue = false
// Now I need to update the view, so it draws rectangle isntead of oval. How I do that?
}
}
And I have my DrawingMethods class:
import Cocoa
public class DrawingMethods: NSObject {
public class func drawOval() {
let color = NSColor(calibratedRed: 1, green: 0, blue: 0, alpha: 1)
let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(64, 54, 50, 45))
color.setFill()
ovalPath.fill()
}
public class func drawRectangle() {
let color = NSColor(calibratedRed: 1, green: 0, blue: 0, alpha: 1)
let rectanglePath = NSBezierPath(rect: NSMakeRect(136, 12, 34, 34))
color.setFill()
rectanglePath.fill()
}
}
So how can i get my custom views draw rectangle instead of oval?
Call
setNeedsDisplayInRect()on the view after settingisTrue = false. This will notify the view that it needs to redraw anddrawRectwill be called again.Your
buttonPressedfunction should be defined in theViewControllerthat contains the custom viewAlternatively, you can just set the
needsDisplayproperty of the view totrueto redraw the entire view: