NSScrollView with horizontal direction using AutoLayout in Interface Builder (MacOS X, Swift 4.2)

This article explains how to create a NSScrollView using AutoLayout in Interface Builder (MacOS X, Swift 4.2)

Not so long time ago I’ve started writing the application for MacOS (I have IOS development background) and faced the problem that most of the answers on my questions were:

  • outdated (answered more than 3 years ago, and consequently, some features were already deprecated)
  • (some answers on Objective C were a little bit painful for my “swifty” eye)
  • answers were for iOS, not for OS X

and sometimes finding of a needed answer is harder than it should be.

So I decided to start writing step-by-step swift tutorials (simple tutorials in format question-answer).

Problem

Content doesn’t fit application window and being cut by view controller.

Solution

To fix this problem you need to add constraints to your views to reach a dynamic width and height of the content.

Okay, let’s start!

Step 1-3.

(Step 1 – on an image below) First of all drag NSScrollView to your ViewController. Then at the left panel in “Attributes Inspector” select (2)Border Typenone and (3) uncheck Draw background.

Step 4.

After, add top/bottom/leading/trailing constraints related to superview. I set a top constraint to 20 because my NSWindow Full Size Content View = true.

Step 5.

Then add your content view(s) (in my case those are 2 Labels wrapped by NSStackView).

Step 6.

Next let’s add the top, leading, trailing constraints and add two bottom constraints to your contentView. I set all constants to 24.

Step 7-8.

Then (7) change first bottom offset relation to Less Than or Equal (≤) and set priority to 490, (8) for the second bottom offset relationGreater Than or Equal (≥), priority to 510.

Step 9.

(9) In addition to that, I added a minimum contentView width 500 (width constant = 500 with relation Greater Than or Equal).

Step 10-11.

For documentView of scrollView add the top, leading, two trailing and two bottom constraints. (10) Set first trailing offset relation as Less Than or Equal and set priority to 510, for second relationGreater Than or Equal, priority to 490. (11) And do the same for bottom constraints.

Step 12.

At last, you should change the isFliped property to a true value for NSClipView.

NSScrollView using AutoLayout result

Consequently, we have a simple application with dynamic content size.

NSScrollView using AutoLayout in Interface Builder  MacOS X

That’s it.
I hope this article about NSScrollView using AutoLayout was helpful to you.
You can find the source code here


Check my next articles: how to create own custom xCode Template or Handling Internet Connection reachability in iOS.


You may check my apps.


If you have any questions or spot any errors please let me know.

Written with ❤️ by Rita