我目前正在尝试以纯编程方式重建现有项目(没有storyboard和nib文件).我知道已经有一些帖子,但他们并没有真正帮助我.这是一种解决方法:
main.swift
import Cocoa
let delegate = AppDelegate()
NS Application.shared().delegate = delegate
let ret = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)`
Run Code Online (Sandbox Code Playgroud)
AppDelegate.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
let viewController = ViewController()
let window = NSWindow(contentRect: NSMakeRect(0, 0, NSScreen.main()!.frame.size.width, NSScreen.main()!.frame.size.height), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: NSBackingStoreType.buffered, defer: false)
func applicationDidFinishLaunching(_ aNotification: Notification) {
viewController.view = NSView(NSMakeRect(0, 0, window.frame.size.width, window.frame.size.height))
viewController.view.wantsLayer = true
window.contentView!.addSubview(viewController.view)
window.makeKeyAndOrderFront(nil)
}
}
Run Code Online (Sandbox Code Playgroud)
ViewController.swift
import Cocoa
class ViewController: NSViewController {
override func viewDidAppear() {
let button = NSButton(frame: NSRect(x: 150, y: 200, width: 300, height: 30))
button.action = #selector(ViewController.buttonPressed(_:))
button.target = self
view.addSubview(button)
}
func buttonPressed(_: Any?) {
print("OK")
}
}
Run Code Online (Sandbox Code Playgroud)
稍后,计划是在不同的视图控制器之间切换这些按钮并显示不同的视图.这是正确的方式还是有"更好"的方式来做到这一点?我的目标是拥有一个窗口和不同的ViewControllers.谢谢您的帮助
target您还需要在按钮上设置。告诉action它要调用哪个方法,但是如果没有目标,它就无法调用该方法。
您可能还需要更改操作方法以允许参数sender:func buttonPressed(_: Any?) {...}并将操作设置为#selector(ViewController.buttonPressed(_:))。
我还刚刚注意到您的视图控制器仅保存在applicationDidFinishLaunching. 它应该是 的属性,AppDelegate以便有对它的引用,否则它将立即被删除。
| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |