如何解决NSView draw() 被调用两次
我是 swift 和 Cocoa 开发的新手,我的问题是:-
NSView 的 draw() 函数被调用了两次。结果和代码如下:-
结果
[3/3] Linking MyCanvasApp
Hello,World
You got nothing.
You got nothing.
^C
正如你所看到的“你什么都没有”被打印了两次
PS 一切都是手写的 我根本没有使用 Xcode
main.swift
import Cocoa
var app = NSApplication.shared
app.setActivationPolicy(.regular)
let delegate = AppDelegate()
app.delegate = delegate
app.activate(ignoringOtherApps: true)
app.run()
AppDelegate.swift
import Cocoa
class AppDelegate: NSObject,NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
print("Hello,World")
let frame = NSRect.init(x: 100.0,y: 100.0,width: 300.0,height: 300.0)
let win = NSWindow.init(contentRect: frame,styleMask: [.closable,.titled],backing: .buffered,defer: false)
win.title = "My Canvas App"
win.makeKeyAndOrderFront(nil)
let frame2 = NSRectToCGRect(NSRect.init(x: 0,y: 0,height: 300.0))
let canvas = CanvasView.init(frame: frame2)
win.contentView!.addSubview(canvas)
}
}
NSView.init (CanvasView.init) 调用它还是什么? ^^
CanvasView.swift
import Cocoa
class CanvasView: NSView {
var Mode: CanvasMode = CanvasMode.Rectangle
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
// super.draw(rect)
// var context: CGContext = NSGraphicsContext.current!.CGContext
self.wantsLayer = true
self.layer?.backgroundColor = NSColor.yellow.cgColor
switch Mode {
case .Line:
print("You got Line.")
default:
print("You got nothing.")
}
}
override func mouseDown(with theEvent: NSEvent) {
print("left mouse")
}
override func rightMouseDown(with theEvent: NSEvent) {
print("right mouse")
}
override func mouseDragged(with theEvent: NSEvent) {
print("mouseDragged")
}
}
CanvasMode.swift
import Cocoa
enum CanvasMode {
case Line
case Rectangle
case Triangle
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。