shah.shah shah.shah - 6 months ago 13
Swift Question

How can I draw a simple line?(OS X)

I tried this:

import Cocoa

class ViewController: NSViewController {

@IBOutlet weak var butt: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func buttPressed(sender: AnyObject) {
let myPath = NSBezierPath()
myPath.moveToPoint(CGPoint(x: 20, y: 20))
myPath.lineToPoint(CGPoint(x: 100, y: 100))
myPath.stroke()
}

}


It compiles and runs but doesn't draw anything when the button is clicked.
I tried setting the color:
NSColor.redColor().set()
, setting the width:
myPath.lineWidth = 20
and using
NSPoint
instead of
CGPoint
but still the same thing happens. What is it that I'm missing?
Thank you for your answers in advance and sorry for the elementary question.

Answer

Try doing it inside drawRect (NSView):

import Cocoa

final class Line: NSView {
    override func drawRect(dirtyRect: NSRect) {
        let myPath = NSBezierPath()
        myPath.moveToPoint(CGPoint(x: 20, y: 20))
        myPath.lineToPoint(CGPoint(x: 100, y: 100))
        myPath.stroke()
    }
}

final class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        let line = Line(frame: frame)
        view.addSubview(line)
    }

    override var representedObject: AnyObject? {
        didSet {
            // Update the view, if already loaded.
        }
    }

}
Comments