NSToolbar灵活空间在Swift 5.x中不起作用

问题描述

我使用Xcode 10.1(我相信是Swift 4.2)开发了此应用,工具栏看起来也不错:

enter image description here

但是我移植到了Xcode 11.6(我相信是Swift 5.2),现在工具栏上最右边的项目不再位于最右边:

enter image description here

在端口之前,我添加了加号按钮-复选框(“显示隐藏”)是第一个项目,此后从未更改。 这些按钮的功能也与预期的一样,它们的动作正常。 注意:此应用程序不使用情节提要或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,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将其设置为应用程序工具栏。

谁能看到导致上述问题的我的代码问题? 否则,这是一个错误吗?

解决方法

在 Swift 5.0 中遇到了同样的问题......即使文档说 minSize 和 maxSize 已被弃用,我还是这样解决了:

let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier.flexibleSpace)
toolbarItem.minSize = NSSize(width: 1,height: 1)
toolbarItem.maxSize = NSSize(width: 1000,height: 1) //just some large value
return toolbarItem

也许这也适用于 Swift 5.2