I am having troubles getting my subviews to resize correctly using Autolayout. To illustrate my point, I put together a minimalistic example.
First I created a new NSViewController and added a subview to it (in this particular case an NSTextView) and added Autolayout constraints.
I then added a custom view to my MainMenu.xib and set up Autolayout constraints for that too.
Finally, I created an instance of my view controller and put its view inside my custom view.
#import "AppDelegate.h"
#import "MyViewController.h"
@interface AppDelegate()
@property (weak) IBOutlet NSView *customView;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[self.customView addSubview:myViewController.view];
myViewController.view.frame = self.customView.bounds;
}
@end
Since "Autoresizes Subviews" is checked in both xib files, I would expect the NSTextView to resize when I resize the main window. However, it just stays in place.
What am I missing here? This has puzzled me for a few days now.
Thanks, Michael Knudsen
Just in case anybody else runs into the same problem. I ended up solving it this way (thanks to @SevenBits for pointing me in that direction).
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[self.customView addSubview:myViewController.view];
myViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subView]|"
options:0
metrics:nil
views:@{@"subView" : myViewController.view}];
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subView]|"
options:0
metrics:nil
views:@{@"subView" : myViewController.view}];
[self.customView addConstraints:verticalConstraints];
[self.customView addConstraints:horizontalConstraints];
}
Your NSTextView's containing view does not have any constraints to its parent, in this case your window. The view that you added is not getting resized, because since your view is not "connected" via constraints to its parent. You might want to investigate the addConstraint:
method if you want to do this programmatically.
See Apple's docs for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With