为什么这个快速代码不显示文本字段?

问题描述 投票:0回答:1

代码应该只显示“Hello, World!”在窗口中。出现窗口但未显示文本。这是为什么?

我可以看到

window.makeKeyAndOrderFront(nil)
甚至命令文本字段在前面查看。

错误:没有错误或警告

import Cocoa

@main
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var window: NSWindow!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create a new window
        window = NSWindow(contentViewController: TextFieldViewController())
        // Make the window visible
        window.makeKeyAndOrderFront(nil)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }
}

class TextFieldViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a label
        let label = NSTextField(labelWithString: "Hello, World!")
        label.frame = NSRect(x: 20, y: 100, width: 200, height: 20)
        // Add the label to the view
        view.addSubview(label)
    }
}
swift xcode cocoa nstextfield nsviewcontroller
1个回答
0
投票

您应该覆盖

loadView
,并在那里添加标签

override func loadView() {
    let view = NSView(frame: NSMakeRect(0,0,400,400))
    self.view = view

    let label = NSTextField(labelWithString: "Hello, World!")
    label.frame = NSRect(x: 20, y: 100, width: 200, height: 20)
    
    view.addSubview(label)
}

这是因为

loadView
的默认实现会查找 nib 文件,而您可能没有且不想使用该文件。

NSViewController
的文档说:

但在 macOS 10.10 及更高版本中,

loadView()
方法会自动查找与视图控制器同名的 nib 文件。

另请参阅

loadView
的文档:

例如,如果您有一个名为 MyViewController 的视图控制器子类和一个同名的 nib 文件,则可以采用方便的初始化模式

[[MyViewController alloc] init]

© www.soinside.com 2019 - 2024. All rights reserved.