Swift 正在调用两次NSView draw()
我是swift的新手,我的问题是:- NSView的draw()函数被调用了两次。结果和代码如下:- 结果Swift 正在调用两次NSView draw(),swift,macos,cocoa,nsview,Swift,Macos,Cocoa,Nsview,我是swift的新手,我的问题是:- NSView的draw()函数被调用了两次。结果和代码如下:- 结果 [3/3] Linking MyCanvasApp Hello, World You got nothing. You got nothing. ^C 正如你所看到的,“你一无所获”被打印了两次 PS所有东西都是手写的我根本不用Xcode 梅因·斯威夫特 import Cocoa var app = NSApplication.shared app.setActivationPoli
[3/3] Linking MyCanvasApp
Hello, World
You got nothing.
You got nothing.
^C
正如你所看到的,“你一无所获”被打印了两次
PS所有东西都是手写的我根本不用Xcode
梅因·斯威夫特
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, width: 300.0, height: 300.0))
let canvas = CanvasView.init(frame: frame2)
win.contentView!.addSubview(canvas)
}
}
NSView.init(CanvasView.init)调用它还是什么^^
斯威夫特
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")
}
}
斯威夫特
import Cocoa
enum CanvasMode {
case Line
case Rectangle
case Triangle
}
如果画了两次,会有什么伤害?
draw
应该画,没有别的,“你应该尽可能快地实现这个方法,并且尽可能少地做工作。”。在init(frame:CGRect)
或其他地方进行设置。AppKit将随时调用draw
。rect
的值是多少?调用draw
是因为更改图层引起的吗?@Willeke我是初学者,假设有什么不对劲。感谢您的澄清,是的,这是由图层更改引起的。删除图层代码修复了它,谢谢