How to hidden the sub NSView according to the window size in Mac OS?

260 views Asked by At

I am coding an MacOS app with swift. The main layout in the window is like follows:

The layout of the app

The NSStackView has a sideBar (NSTableView) and a NSView. What I want to achieve is listed here:

  1. The width of the sideBar is fixed when changing the window size.
  2. When the width of the window is smaller than WIDTH_THRESHOLD, the sideBar is hidden.

The problems are

  1. For Target 1, the constraints of the sideBar and the NSView is like follows, but it doesn't work and the width of the sideBar still changes.

The constraints

  1. For Target 2, the project has a NSWindowController and a NSViewController. I can listen the window size in NSWindowController, but I don't know how to transport this msg to the NSViewController to hidden the sideBar.

Notice that NSStackView has the properties like Hugging Priority, Clipping Resistance Priority and Visibility Priorities in size inspector, can I achieve the targets through setting these properties (in the following figure)?

The properties

2

There are 2 answers

0
Knaoinr On
  1. Have you constrained the width of the sidebar? If you haven't, what may be happening is that the NSView is autoresizing and pushing the sidebar around. Changing the red arrows doesn't create actual constraints, just changes the resizing rules.

  2. Listen to the window size in your NSWindowController, just like you said. As long as you have a reference to your side bar available in that window class (e.g. you can access the view controller that contains it), you can set sideBar.isHidden = true when the window gets too small, and false when the window is large enough again.

0
david On
  1. Finally, I use NSSplitView as the sideBar and it is much easier.

  2. I use NSSplitViewDelegate to listen the width change of the SplitView.