NSScrollView with auto layout not resizing until first manual window resize

浪尽此生 提交于 2019-11-28 12:43:06

I've worked out an answer - I'm not entirely happy with it, but it seems to work.

There are certain Cocoa widgets that don't deal well with autolayout - in particular, I've found problems with top level NSWindows and NSTabViewItems; I'm guessing other widgets might also be affected. Essentially, these are "container" widgets that have a top level "view" that must be set. If the "contained" widget is an NSScrollView (which itself will contain other widgets), the "container" widget has difficulty establishing a size for the "contained" scroll view.

The fix is to re-enable translatesAutoresizingMaskIntoConstraints for the view that will be used as the "contained" widget. In the example provided, the object scroll_view created on line 10 is the "contained" widget; the boolean value of the call to setTranslatesAutoresizingMaskIntoConstraints on line 15 should be True, not False.

These problems get better with more recent versions of OS/X - Mavericks doesn't have a problem with NSWindow, but it still has a problem with NSTabViewItem. However, it doesn't seem to do any damage to turn on translatesAutoresizingMaskIntoConstraints on newer versions of OS X; all you're losing it the theoretical purity of a 100% autolayout solution.

The real issue is that some of your controls are fixing the size of the view and thus for the window. For example, if you have only one view, say view1 inside your viewcontroller's view, and:

  • set leading/trailing/top/bottom to the main view and
  • view1.height = 300,

this will make your window size to be fixed to 300 and thus not resizeable.

Look at Apple's 2012 developer conference videos about Auto Layout for information about using Auto Layout in code.

Simply use in Interface Builder or in code the approach I recorded in this video tutorial:

How to use NSScrollView with Auto Layout

This is the approach I used in this video:

  1. Window -- set delegate and IBOutlet property

  2. ScrollView -- fixed edges, no border, don't draw background

  3. documentView -- fixed edges 0, then another trailing and bottom, clipView ≥ 0 @499 and clipView ≤ 0 @501 for both trailing and bottom constraints to documentView

  4. label and text field in horizontal stack view, in vertical stack view

  5. vertical stack view fixed edges default, then another bottom, bottom ≤ default @499 and ≥ default @750

  6. horizontal stack view leading and trailing fixed 0

  7. label and text field align Y center to horizontal stack view

  8. text field top and bottom and trailing 2 @750, width ≥ 100, height ≥ 22

  9. subsequent horizontal stack views leading and trailing fixed, align text field leadings

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