如果未设置NIB“使用Autolayout”,我可以使用NSLayoutConstraint吗?

时间:2013-01-23 10:03:52

标签: macos autolayout

我现有的Mac应用程序使用Springs和Struts并且运行良好,但我想在我的一个NIB中的单个视图中使用“Auto Layout”。我将以编程方式提供这些约束(因为使用IB配置约束是一个完整的噩梦)。

我的问题是我可以在我的视图中设置NSLayoutConstraint个对象,当它包含在未使用“使用Autolayout”的NIB中时吗?

1 个答案:

答案 0 :(得分:0)

好的,所以对这个问题的简短回答是“是”即使NIB已关闭“使用自动布局”,也可以使用NSLayoutConstraint

这是我的观点awakeFromNib方法:

- (void)awakeFromNib
{
    NSDictionary *viewsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                     _field1, @"field1",
                                     _field2, @"field2",
                                     _field3, @"field3",
                                     nil];

    // Turn off conversion of Springs and Struts into NSLayoutConstraints for all the controls
    for (NSControl *control in [viewsDictionary allValues])
    {
        [control setTranslatesAutoresizingMaskIntoConstraints:NO];
    }

    NSString *hformat = @"H:|-4-[field1(>=48)]-[field2]-[field3(==field1)]-4-|";
    NSArray *hconstraints = [NSLayoutConstraint constraintsWithVisualFormat:hformat
                                                                    options:0
                                                                    metrics:0
                                                                      views:viewsDictionary];

    [self addConstraints:hconstraints];

    // Vertical layout (must be done for each control separately)
    for (NSString *controlName in [viewsDictionary allKeys])
    {
        NSString *vformat = [NSString stringWithFormat:@"V:|-4-[%@]", controlName];
        NSArray *vconstraints = [NSLayoutConstraint constraintsWithVisualFormat:vformat
                                                                        options:0
                                                                        metrics:0
                                                                          views:viewsDictionary];

        [self addConstraints:vconstraints];
    }
}


    // Other init
}

一些注意事项:

  • 远远超过上面显示的字段;我简化了在此发布的代码。
  • 相关视图位于拆分视图中,为了在超级视图调整大小时正确调整其大小,我确实调用[self setTranslatesAutoresizingMaskIntoConstraints:NO];
  • 您需要停止使用自动布局约束所有子视图的Springs和Struts的转换。
  • 其他拆分视图窗格中有一个滚动视图,我不得不在该滚动视图上调用setTranslatesAutoresizingMaskIntoConstraints:NO,否则会引发异常。