使用“自动版式”,(至少)有三种方法可以约束视图,使其占据整个窗口的内容视图,并在适当时调整大小。
关于超级视图的视觉格式约束
NSView *contentView = [_window contentView];
MyView *customView = [[MyView alloc] initWithFrame:[contentView bounds]];
[customView setTranslatesAutoresizingMaskIntoConstraints:NO];
[contentView addSubview:customView];
NSDictionary *views = NSDictionaryOfVariableBindings(customView);
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[customView]|"
options:0
metrics:nil
views:views]];
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[customView]|"
options:0
metrics:nil
views:views]];
边缘的程序约束
(这应与上面的视觉格式等效)
+ (void)addEdgeConstraint:(NSLayoutAttribute)edge superview:(NSView *)superview subview:(NSView *)subview {
[superview addConstraint:[NSLayoutConstraint constraintWithItem:subview
attribute:edge
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:edge
multiplier:1
constant:0]];
}
和
NSView *contentView = [_window contentView];
MyView *customView = [[MyView alloc] initWithFrame:[contentView bounds]];
[customView setTranslatesAutoresizingMaskIntoConstraints:NO];
[contentView addSubview:customView];
[[self class] addEdgeConstraint:NSLayoutAttributeLeft superview:contentView subview:customView];
[[self class] addEdgeConstraint:NSLayoutAttributeRight superview:contentView subview:customView];
[[self class] addEdgeConstraint:NSLayoutAttributeTop superview:contentView subview:customView];
[[self class] addEdgeConstraint:NSLayoutAttributeBottom superview:contentView subview:customView];
程序限制大小
NSView *contentView = [_window contentView];
MyView *customView = [[MyView alloc] initWithFrame:[contentView bounds]];
[customView setTranslatesAutoresizingMaskIntoConstraints:NO];
[contentView addSubview:customView];
[contentView addConstraint:
[NSLayoutConstraint constraintWithItem:customView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:contentView
attribute:NSLayoutAttributeWidth
multiplier:1
constant:0]];
[contentView addConstraint:
[NSLayoutConstraint constraintWithItem:customView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:contentView
attribute:NSLayoutAttributeHeight
multiplier:1
constant:0]];
第三种方法是问题中列出的方法,如果存在进一步的限制,它可能不起作用。例如,没有:
[customView setTranslatesAutoresizingMaskIntoConstraints:NO];
原始的autoresize蒙版也将应用,这会导致问题中描述的行为:不调整窗口大小。
如Regexident所述,您可以使用:
[_window visualizeConstraints:[contentView constraints]];
调试自动版式。同样值得检查控制台输出。
[[contentView constraints].window visualizeConstraints:contentView.constraints];