我无法在OS X上使用“自动布局”。我想做的很简单,即我有一个NSTextField,应该填充其超级视图的整个空间。这是我正在使用的最小工作示例代码:

@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;
}


当我运行它时,文本字段不会出现。调整窗口大小时,您可以清楚地看到内容视图的边框大小正确调整。我究竟做错了什么?

最佳答案

我相信您不应该更改NSWindowcontentView行为,例如设置其translatesAutoresizingMaskIntoConstraints属性。

删除以下行对我有用:

window.contentView.translatesAutoresizingMaskIntoConstraints = NO;

关于macos - 在OS X上自动布局-使NSTextField填充 super View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34465587/

10-11 19:47
查看更多