我使用 Xcode 10.1(我相信是 Swift 4.2)开发了这个应用程序,工具栏看起来不错:
但是我移植到我的 Xcode 11.6(我相信是 Swift 5.2),现在工具栏上最右边的项目不再位于最右边:
在移植之前,我添加了加号按钮 - 复选框(显示隐藏)是第一个项目之一,此后从未更改过。按钮也按预期工作 - 他们的动作可以触发。注意:这个应用程序不使用故事板或 IB 的东西。
由于我的代码拆分为多个文件(包含许多不相关的代码),因此我将进行概述。
class ToolbarController: NSObject, NSToolbarDelegate {
let toolbar = NSToolbar(identifier: NSToolbar.Identifier("toolbar"))
lazy var toolbarItem1: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier(rawValue: "Btn1"))
let button = NSButton(frame: NSRect(x: 0, y: 0, width: 40, height: 1))
button.target = self
...
toolbarItem.view = button
return toolbarItem
}() // defined as "lazy" to allow "self"
var toolbarItemSpace: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier.space)
return toolbarItem
}()
...
var toolbarItemFlexSpace: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier.flexibleSpace)
return toolbarItem
}()
lazy var toolbarItemShowHidden: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier(rawValue: "Checkbox"))
let box = NSBox(frame: NSRect(x: 0, y: 0, width: 120, height: 40))
let button = NSButton() // put in NSBox to use isolated action
...
button.target = self
box.contentView = button
box.sizeToFit() // tightly fit the contents (button)
toolbarItem.view = box
return toolbarItem
}()
lazy var tbItems: [NSToolbarItem] = [toolbarItem1, ...]
该类定义工具栏、添加项目、实现所有这些工具栏(委托)方法并使其成为委托。然后我的 NSWindowController 将其设置为应用程序工具栏。
任何人都可以看到导致上述问题的我的代码问题吗?否则,这是一个错误吗?