I am adding some simple constraints to an NSView that I have in my main NSWindow but it is causing problems.
Normally I can resize my application window (just like any Safari/Finder window etc.). I add a simple NSView to my window like so:
[self.blackDimOverlay setFrame:NSMakeRect(0, 0, self.window.frame.size.width, self.window.frame.size.height)];
[self.blackDimOverlay setAlphaValue:0.5f];
[self.window.contentView addSubview:self.blackDimOverlay];
This works as expected. I then add two constraints to this view so that it stays the full size of the window when resized.
NSDictionary *viewsDict = NSDictionaryOfVariableBindings(_blackDimOverlay);
NSArray *constraintHorizontalOverlay = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[_blackDimOverlay]-0-|" options:0 metrics:nil views:viewsDict];
NSArray *constraintVerticalOverlay = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[_blackDimOverlay]-0-|" options:0 metrics:nil views:viewsDict];
[self.window.contentView addConstraints:constraintHorizontalOverlay];
[self.window.contentView addConstraints:constraintVerticalOverlay];
However, after adding these two constraints, they lock my window up, so I can't resize it anymore. Everything else works as normal, but the constraints block any window resizing.
How can I keep my subview the full-size of my window while being able to resize my window?
Thanks.
There are additional constraints on _blackDimOverlay which dictate its size and are of higher priority than NSLayoutPriorityDragThatCanResizeWindow. You can investigate using:
NSLog(#"%#", [self.window.contentView constraintsAffectingLayoutForOrientation:NSLayoutConstraintOrientationHorizontal]);
NSLog(#"%#", [self.window.contentView constraintsAffectingLayoutForOrientation:NSLayoutConstraintOrientationVertical]);
Most likely, you forgot to do [_blackDimOverlay setTranslatesAutoresizingMaskIntoConstraints:NO].
Alternatively, the view class of which _blackDimOverlay is an instance defines an intrinsic size and its hugging and compression-resistance priorities are higher than NSLayoutPriorityDragThatCanResizeWindow. You would need to reduce those priorities using -setContentHuggingPriority:forOrientation: and -setContentCompressionResistancePriority:forOrientation:.
Related
I'm try resize window for two display.
On yosemite much depends on the [NSScreen screensHaveSeparateSpaces] - "Displays have separate Spaces" setting.
If screensHaveSeparateSpaces is set to NO, I can resize NSWindow to all screens, and set [window setLevel:CGShieldingWindowLevel()], and this will work.
But if screensHaveSeparateSpaces is set to YES, I only see half of the window. I'm trying:
NSDictionary *opts = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSFullScreenModeAllScreens,
nil];
NSView *view = [window contentView];
[view enterFullScreenMode:[NSScreen mainScreen] withOptions:opts];
NSRect frame = [view.window frame];
frame.size.width *= 2;
[view.window setContentSize:frame.size];
NSView resize to all screen this is true, but NSView fills my left-hand primary display - the secondary (right hand) display stays black.
How can I resize NSView to fullscreen (dual display) if screensHaveSeparateSpaces is returning YES?
You can't. A window exists in one space only. If each screen has a separate space, then you can't have one window on both screens. Your best bet would be to try to fake it by having two windows, one in each space, but I'm not even sure that would be possible. Assuming you can even have an app with windows in multiple spaces, it'd be non-trivial to try and keep the two windows in sync with each other.
In Interface Builder I've added a NSScrollView with a NSImageView, some labels, a horizontal separator and a NSView. The NSScrollView looks like the following:
Every element has constraints from the top left, and both the separator and the custom view also have a constraints to the right.
Sometimes I need to change the content of the custom view. I do this with the following code (options is the custom view, view is the view I want to display):
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
options.subviews = [NSArray arrayWithObject:view];
// Fix the constraints.
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(view);
[options addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[view]|" options:0 metrics:nil views:viewsDictionary]];
[options addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[view]|" options:0 metrics:nil views:viewsDictionary]];
This works to some extent: the correct content is displayed in the view and the content's width is changed according to the constraints. However, the height of the options view doesn't change, so some content of the view view is not displayed. I tried to change this by manually setting the frame, but that doesn't work. Also, I tried the following to set a constraint:
[options addConstraint:[NSLayoutConstraint constraintWithItem:options attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeHeight multiplier:1 constant:0]];
Nothing works though. Does anyone know how I can fix this?
A second problem I noticed is that even when the content of the NSScrollView is larger than the NSScrollView itself, scrolling doesn't work. No scrollbar is displayed. How can I fix that?
I still can't get my head around these harder problems with constraints...
I managed to solve my problem. It turned out I really had two problems:
I didn't set the correct constraints on the NSScrollView and its children;
I changed the content of the custom view, but didn't change its height.
My fix to both problems follows below.
NSScrollView constraints
After adding a NSScrollView in Interface Builder and placing some UI elements in the document view (the clip view's child), I had the following interface (the white part of the window is the NSScrollView, don't look at the constraints for now):
If you run this and resize the window, no scrollbars are displayed though. First of all we have to add top and leading constraints on the document view relative to its superview. Now we need to specify the size of the document view. This can be done in two ways, depending on your use-case:
Add constraints for the width and height of the document view. This way the same scrollbars are always displayed. The document view will then not change size depending on the content though, unless you automatically update these constraints;
Add constraints to every child of the document view, so that document view's width and height can be calculated. This was needed for my problem, and these constraints are displayed in the image above.
If you run this, everything works as expected. We still can't change the content of the custom view though, and that's a different problem.
Changing the custom view
Now we just need to change the content of the custom view. Since we set constraints on the custom view, these should also be changed. All of this is done with the following self-explanatory code (the custom view is named content):
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[content setAutoresizesSubviews:NO];
}
- (IBAction)button1:(id)sender {
[self showContent:view1];
}
- (IBAction)button2:(id)sender {
[self showContent:view2];
}
- (void)showContent:(NSView *)c {
// Remove all constraints.
[content removeConstraints:content.constraints];
// Add a height constraint.
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:content attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:c.frame.size.height];
[content addConstraint:constraint];
// Add a width constraint.
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:content attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:c.frame.size.width];
[content addConstraint:constraint];
[c setTranslatesAutoresizingMaskIntoConstraints:NO];
// Set the content.
content.subviews = [NSArray arrayWithObject:c];
// Add constraints from the content view to its child view.
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(c);
[content addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[c]|" options:0 metrics:nil views:viewsDictionary]];
[content addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[c]|" options:0 metrics:nil views:viewsDictionary]];
}
I hope this answer saves someone else the trouble of finding out about the strange behavior with NSScrollView and autolayout.
I have an NSWindow that has 2 container views within it, all in one xib, like so:
In another xib, I have a the view for the sidebar, managed by a different view controller, like so:
When I add the subview to the container view, I do it like this:
self.sidebarViewController.view.frame = self.sidebarContainer.bounds;
[self.sidebarContainer addSubview:self.sidebarViewController.view];
When I build and run, and resize this window, this is what happens:
The container tracks the height of it's superview properly, but the sidebar view itself does not track the height of the container.
How can I set things up so that the height of the sidebarVCs' view tracks the height of the container as the window is resized?
I think I've solved it like so:
[self.sidebarViewController.view setTranslatesAutoresizingMaskIntoConstraints:NO];
NSLayoutConstraint *w = [NSLayoutConstraint constraintWithItem:self.sidebarViewController.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:150.0];
NSArray *c1 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[view]|"
options:0
metrics:nil
views:#{ #"view":self.sidebarViewController.view }];
[self.sidebarContainer addConstraints:c1];
[self.sidebarContainer addConstraint:w];
I still don't yet understand why the autoresizemask layout constraint doesn't do this automatically, but I think I'm closer to understanding the relationships between the views here.
Use NSBoxes as containers. In your sidebar, add an NSBox inside the NSView and constrain all sides to the view. Then when you want to swap in a view for the side bar you can call container (the NSBox object) setContentView:.
So I've seen this question asked a couple times, but haven't come across an answer that solves my problem. Right now I basically have MainMenu.xib with a label centered on the top, a large custom view and a button centered on the bottom that switches subviews of the custom view (see picture below). I've set the window and the custom view to autoresize subviews in the interface builder and all the buttons, labels, etc. have constraints relating them to the sides of the view, but when I resize the window, the contents of the subview do not resize. I think the custom view is resizing with the window because when I switch subviews with the button, the subview that loads is resized with the window, they just aren't resizing with the window in real time.
MainMenu.xib:
Normal subview:
After window is expanded:
Subview switched and then switched back:
CONSTRAINTS:
MainMenu.xib:
BlockViewController.xib:
Figured it out! Really simple, just one line of code in the awakeFromNib method of each ViewController subclass:
[self.view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
From the pictures and the description in the comments it seems that the problem is that the custom view does not get any layout constraints to determine how to resize the subview.
The following piece of code (typed directly in the browser, so beware) should provide the necessary constraints to "glue" the borders of the subview to the custom view.
[self.customView addSubview: self.blockSubView.view];
self.blockSubView.view.frame = self.customView.bounds;
NSView *blockSubView = self.blockSubView.view;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(blockSubView);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"|[blockSubView]|"
options:0
metrics:nil
views:viewsDictionary];
constraints = [constraints arrayByAddingObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat:#"V|[blockSubView]|"
options:0
metrics:nil
views:viewsDictionary]];
[self.customView addConstraints: constraints];
There is more about this in the docs. Notice the tricks for debugging - very useful to the point of being indispensable.
I am having a problem with the new Auto Layout functionality.
I add an NSView called tableView as a subview of workingBox. workingBox also contains some other subviews that were added with Interface Builder
[self.window setFrame:frame display:YES animate:YES];
[workingBox addSubview:tableView];
My problem is that if any of the other subviews touch tableView then they will get resized in the animation. The subviews that are not near where tableView is being added remain the correct size. I have already tried setting NSViewNotSizable resizeMask on the subviews that are getting resized but it does not work. The only thing that works is moving the subview upwards (into the wrong position.
EDIT: I have added a constraint in code:
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(divider);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:[divider(==1)]"
options:0
metrics:nil
views:viewsDictionary];
[workingBox addConstraints:constraints];
This keeps the NSView at 1px height but if I lock it to the top it prevents the superview growing
I could not make this work by adding a constraint in code. However in Interface Builder I could see that there was a constraint for the NSView in question that was named 'Bottom Alignment'. I changed this to a priority of 1 in the inspector and it stopped the NSView getting stretched down when the window expanded. I think this auto added constraint that I mentioned in my comment above had been the problem all along.