我无法让Auto Layout在OS X上运行。我正在尝试做的非常简单,即我有一个NSTextField应该填充其superview的整个空间。这是我正在使用的最小工作示例代码:
@import AppKit;
int main() {
@autoreleasepool {
NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 300, 300)
styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask)
backing:NSBackingStoreBuffered
defer:NO];
NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
textField.stringValue = @"Lorem ipsum dolor sit atmet.";
[window.contentView addSubview:textField];
textField.translatesAutoresizingMaskIntoConstraints = NO;
window.contentView.translatesAutoresizingMaskIntoConstraints = NO;
[textField setContentHuggingPriority:1
forOrientation:NSLayoutConstraintOrientationHorizontal];
[textField setContentHuggingPriority:1
forOrientation:NSLayoutConstraintOrientationVertical];
[window.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[textField]-|"
options:0
metrics:nil
views:@{@"textField": textField}]];
[window.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[textField]-|"
options:0
metrics:nil
views:@{@"textField": textField}]];
window.contentView.wantsLayer = YES;
window.contentView.layer.borderWidth = 5;
[window makeKeyAndOrderFront:nil];
[[NSApplication sharedApplication] run];
[textField release];
[window release];
}
return EXIT_SUCCESS;
}
运行时,文本字段不会出现。调整窗口大小时,可以清楚地看到内容视图的边框正确调整大小。我做错了什么?
答案 0 :(得分:1)
我相信你不应该改变NSWindow
的{{1}}行为,例如设置其contentView
属性。
删除以下行对我有用:
translatesAutoresizingMaskIntoConstraints