在 setNeedsLayout:YES 后未调用 NSView 布局方法

nrj*_*nrj 5 layout cocoa objective-c nsview

从 OSX 10.7 开始,如果您希望执行 NSView 的手动布局,您应该通过覆盖该layout方法来实现,并且每当您希望安排对该方法的调用时,您只需执行以下操作:

[myView setNeedsLayout:YES] 
Run Code Online (Sandbox Code Playgroud)

我对 iOS 中的这种模式非常熟悉,但是在 OSX 上它似乎不起作用。我创建了一个自定义 NSView 并实现了layout它,但它似乎永远不会被调用。曾经。不是在添加子视图之后,不是在调用之后setNeedsLayout:YES,永远不是,我不知道为什么。我可以手动打电话layout,事情按预期工作,但文档说永远不要这样做。

从Xcode:

- (void)layout
Override this method if your custom view needs to perform custom
layout not expressible using the constraint-based layout system. In
this case you are responsible for calling setNeedsLayout: when
something that impacts your custom layout changes.
Run Code Online (Sandbox Code Playgroud)

来自在线文档:

仅当您想要进行自定义布局时才应该覆盖布局。如果你这样做,那么你还需要调用 setNeedsLayout: 当输入到你的自定义布局的东西发生变化时。

链接:http : //developer.apple.com/library/mac/#releasenotes/UserExperience/RNAutomaticLayout/#//apple_ref/doc/uid/TP40010631-CH1-SW14

任何帮助深表感谢。

更新: 这是一个示例 Xcode 项目的链接,该项目说明了LayoutTest.zip问题

Der*_*rek 2

您需要启用自动布局。如果您使用的是 xib 文件(您应该这样做,没有突击队!),您可以在文件检查器的 Interface Builder Document 部分中选中自动布局复选框。

在代码中: [myView setTranslatesAutoresizingMaskIntoConstraints:YES]

在您的示例项目中,您没有任何限制。如果没有任何约束,视图不会调用布局。

NSView *aView = self.window.contentView;
NSDictionary *viewsDictionary=NSDictionaryOfVariableBindings(aView, complexView);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[aView]-[complexView]" options:0 metrics:nil views:viewsDictionary];

for (NSLayoutConstraint *constraint in constraints) {
    [complexView addConstraint:constraint];
}
Run Code Online (Sandbox Code Playgroud)