NSWindow launching with wrong size after setting contentViewController to NSTabViewController

爱⌒轻易说出口 提交于 2019-12-03 16:20:12

I recently ran into this frustrating problem as well.

There are a couple options to workaround this problem:

  1. As you mentioned, set preferredContentSize in each of your custom view controllers that hold the tab's content to your desired size. This is inflexible but it does work.

    // Swift
    class FooViewController: ViewController {
    
        override func viewWillAppear() {
            super.viewWillAppear()
    
            preferredContentSize = NSSize(width: 400, height: 280)
        }
    }
    
  2. I found a hint to a better solution in this SO answer. You can add a subview (stackview, nsview, etc...) to the main view of the view controller that handles the tab's content (phew!) and then add constraints that pin it to each edge and add constraints that set the size.

Here's a screenshot of what it looks like in Interface Builder. I added a Stack View and then added 6 constraints.

Hope this helps.

I had a similar issue. I added a view controller with a container view as the window content and pointed the container view content to the tab view controller.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!