5

我有一个 Xcode 项目,NSWindowControllercontentViewController被设置为NSViewController. 我最近NSViewController从情节提要中删除了子类并用子类替换contentViewControllerNSTabViewController

现在,当我运行应用程序时,NSWindow打开的大小为 500x500,而不是第一个选项卡的大小。更重要的是,我在故事板中看不到大小为 500x500 的视图,而且该大小也不是以编程方式实现的。窗口本身被设置为不同的大小,就像NSTabViewController's first中的视图一样NSViewController

我假设我必须在某处设置某种约束,但如果有,我不知道在哪里/如何找到它。使用 Xcode 9.2 和 High Sierra。

在工程中以编程方式将窗口的大小设置为正确的大小windowDidLoad(),但如果我改变了视图的大小,我也必须改变它,它会变旧,很快。

抱歉,如果这含糊不清;我真的不知道什么样的屏幕截图或代码片段会有所帮助。

4

3 回答 3

8

我最近也遇到了这个令人沮丧的问题。

有几个选项可以解决此问题:

  1. 正如您所提到的,preferredContentSize在您的每个自定义视图控制器中设置将选项卡的内容保持为您想要的大小。这是不灵活的,但它确实有效。

    // Swift
    class FooViewController: ViewController {
    
        override func viewWillAppear() {
            super.viewWillAppear()
    
            preferredContentSize = NSSize(width: 400, height: 280)
        }
    }
    
  2. 我在这个SO 答案中找到了更好解决方案的提示。您可以将子视图(stackview、nsview 等)添加到处理选项卡内容的视图控制器的主视图(唷!),然后添加将其固定到每个边缘的约束并添加设置大小的约束。

这是Interface Builder 中的屏幕截图。我添加了一个堆栈视图,然后添加了 6 个约束。

希望这可以帮助。

于 2018-04-05T12:09:56.010 回答
4

Joshua's answer with setting the preferredContentSize did the trick, all kudos to him! One remark worth making is that since this is done exclusively for the parent tab view controller it's a good idea to subclass it and move this handling into tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) delegate method, which gets invoked when the tab is selected:

override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
    tabViewItem?.viewController?.preferredContentSize = tabViewItem?.view?.frame.size
    // Alternatively: tabViewItem?.viewController?.preferredContentSize = tabViewItem?.view?.fittingSize
    super.tabView(tabView, didSelect: tabViewItem)
}

This way the preferred content size is always up to date and you can worry not about manually refreshing it, assuming the view provides the correct frame size or fitting size, which is easily achieved with constraints.

This method also get's invoked after the window controller finishes loading and where the 500×500 gets initially set.

Setting the preferred content size in every tabbed view controller itself is not ideal: the same code is duplicated across multiple controllers and adds unnecessary noise if these controllers are reused else where.

于 2019-01-26T14:19:12.123 回答
1

我有一个类似的问题。我添加了一个带有容器视图的视图控制器作为窗口内容,并将容器视图内容指向选项卡视图控制器。

于 2018-05-03T13:55:45.400 回答