I am beginning to pull out my hair: I am trying to create a subview programmatically that would adjust its size automatically when the user resizes the window. More details below.
I have searched the documentation (e.g., Apple "Auto Layout Guide"), searched the internet (and tried to follow a lot of examples on stackexchange), all to no avail.
More specifically, I have a very simple setup that consists of a MasterViewController that has its own XIB.
It's declared like this:
@interface MasterViewController : NSViewController
{
ArtSaverView * saver_;
(there is not much more to it)
It creates a subview programmatically that is an instance of my own class ArtSaverView, which is a subclass of ScreenSaverView, which is a subblass of NSView.
So, my MasterViewController has this method:
- (void) viewDidLoad
{
[super viewDidLoad];
saver_ = [[ArtSaverView alloc] initWithFrame: self.view.frame isPreview: NO ];
[self.view addSubview: saver_];
Now, when the user resizes the window, the view of the ArtSaverView instance does not resize, no matter what I do.
For instance, I have tried this later in the method viewDidLoad:
[saver_ setTranslatesAutoresizingMaskIntoConstraints: NO];
NSDictionary * views = NSDictionaryOfVariableBindings( saver_ );
NSArray * horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[saver_]-0-|"
options: 0 metrics: nil views: views];
NSArray * verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[saver_]-0-|"
options: 0 metrics: nil views: views];
[self.view addConstraints: horizontalConstraints ];
[self.view addConstraints: verticalConstraints ];
[NSLayoutConstraint activateConstraints: horizontalConstraints ];
[NSLayoutConstraint activateConstraints: verticalConstraints ];
But nothing changes.
Is there anything else I can try?
All kinds of hints, insights, pointers will be highly appreciated.
In windowDidResize, you should put the code to:
- change constraints constants if needed (don't create new constraints each time) and call
self.window?.layoutIfNeeded()
- or reset directly the views frames.
First is preferable.
For this,
- your constraints should be declared as class properties.
- They should be initiated in viewDidLoad
- And modified if needed in windowDidResize:
someConstraint.const = newValue