3
votes

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.

1

1 Answers

8
votes

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:.