0

My problem is that I am unable to draw an oval in a view controller using swift for an application being written for OSX.

I have the following code in a view controller:

class TouchController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        //// Color Declarations
        let color2 = NSColor(calibratedRed: 0.769, green: 0.364, blue: 0.364, alpha: 1)

        //// Oval Drawing
        let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(70, 24, 145, 143))
        color2.setFill()
        ovalPath.fill()
    }
}

The code for the drawings were created by paint code. I am writing this for OSX in Swift. My question is why, when I compile the code is the oval not displayed?

Dan J
  • 16,319
  • 7
  • 50
  • 82
Kian Cross
  • 1,818
  • 2
  • 21
  • 41

1 Answers1

2

In Cocoa, implement the drawRect method of NSView to draw in views. Using your existing code, see this Playground-compatible example:

import Cocoa

public class CustomOval : NSView {
    public override func drawRect(dirtyRect: NSRect) {
        let color = NSColor(calibratedRed: 0.769, green: 0.364, blue: 0.364, alpha: 1)
        let path = NSBezierPath(ovalInRect: NSMakeRect(70, 24, 145, 143))
        color.setFill()
        path.fill()
    }
}

var oval = CustomOval(frame: NSRect(x: 0, y: 0, width: 300, height: 300))

See "Drawing Shapes Using Bézier Paths" for more information.

Jacob Budin
  • 9,753
  • 4
  • 32
  • 35
  • Thank you. I copied the class `CustomOval` into a file and then in my view did load put `var oval = CustomOval(frame: NSRect(x: 0, y: 0, width: 300, height: 300))` but it still didn't work. The link you have me had Objective-C examples but I'm writing in swift and don't know objective-c. Sorry for being a n0ob :) – Kian Cross Jul 30 '15 at 00:06
  • 1
    @crossboy007 In this case, you could create an `NSView` in Interface Builder (say, within in your primary application window) and assign the Custom Class to `CustomOval`. If you're just starting, this kind of application development can be very challenging (and frustrating); it may be helpful to spend some time with introductory Cocoa texts before you dive in. – Jacob Budin Jul 30 '15 at 01:54
  • Yes, I should spend some time looking at that. But I very rarely do this kind of development, this is just part of a much bigger project :) I thought it would be very easy to add a circle to an `NSView` using the `NSViewController` file. Is it not possible to do it though the `NSViewController` file? – Kian Cross Jul 30 '15 at 10:02
  • @crossboy007 Sure you can. Add `@IBOutlet weak var oval: CustomOval!` to your `NSViewController` and add a referencing outlet from `oval` to the controller (probably the "File's Owner"). – Jacob Budin Jul 31 '15 at 00:22