How to Add Dynamic Constraints to Your Swift Project
Kyra
Posted on April 8, 2024
I just wanted to start out by saying that this is an abridged version of my original published version from June 9, 2021 that you can find on my website here and at that time I was running Xcode version 12.5 (12E262). I have since switched to primarily SwiftUI but figured I'd still share in case it can help you.
My Problem
At the time I originally posted this I had been working on a MacOS prototype application and was playing around using the Interface Builder with IBOutlets
. There I used a label to display an error message that was conditionally visible or not based on if the user should see that message.
My issue was with the space where the message went. It looked great when visible but when hidden the blank space was still there and didn't shrink down. You can see that space here marked in purple here:
I finally realized the Interface Builder attributes I was adjusting wouldn't be helpful when I noticed the checkbox Remove at build time
.
I checked it off and decided to explore a more programmatically solution.
My Solution
To create the constraints programmatically I knew I needed to access all three of the following controls in question within my back end code and alter which control the bottom NSScrollView
/textview
was constrained with.
After the outlets were connected I next instantiated two new NSLayoutConstraints
right after my outlets:
Next I went to the viewDidLoad
function and added:
Finally I went to where I controlled the visibility and stringValue
of the error message and added the following code to set which constraint was active or not:
The order of this does matter as if the last two lines were reversed I received an error when it was run.
It Works
With the constraints declared, instantiated, and activated (or inactivated) it’s time to test this out. And the space disappeared when the error message was hidden!
I hope this helps you and your coding is going great!
If you want more information about my problem, the solution, or even to come along with me on my search to discover it you can check out entire published version from June 9, 2021 on my website here!
Posted on April 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.