Swift 如何画一条简单的线?(OSX)
我试过这个:Swift 如何画一条简单的线?(OSX),swift,macos,cocoa,swift2,Swift,Macos,Cocoa,Swift2,我试过这个: 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: AnyObjec
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()
}
}
它编译并运行,但单击按钮时不绘制任何内容。
我尝试设置颜色:NSColor.redColor().set()
,设置宽度:myPath.lineWidth=20
,并使用NSPoint
而不是CGPoint
,但仍然发生同样的情况。我错过了什么?
感谢您提前给出的答案,对于这个基本问题,我深表歉意。请尝试在
drawRect
(NSView
)中进行操作:
不确定搜索的内容,但请尝试:“cocoa”“drawing”“example”“swift”。它为我提供了很多页面的示例。试图直接在
viewDidLoad
(myPath.stroke()
)中绘制是没有意义的,因为正如错误告诉您的那样,您无处绘制(无“上下文”)“我正在viewDidLoad中直接绘制”,我告诉您这没有意义。别这样,你还是没有背景。你好像没在听。我不知道你想让这一行去哪里,运行时也不知道。你必须说出来。你必须先有一个地方画画,然后才能画画。@matt那么,我该如何创建上下文呢?如果你把正确的代码作为答案,我会把它标记为接受。
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.
}
}
}