添加哪个视图约束是否重要?

时间:2014-11-12 13:25:27

标签: ios objective-c autolayout ios-autolayout

我发现收集整个视图层次结构的所有约束并将它们全部添加到本地根视图很方便。对于在适当的视图中添加约束,这是否沮丧和/或是一个坏主意?

以下是我使用的常见模式的简化。对于多个存储的约束,视图通常更复杂,需要在添加或删除视图时进行更新。

- (void)updateViewConstraints
{
    UIView *content = ...;
    UIView *panel = ...;
    UILabel *label = ...;
    [self.view addSubview:content];
    [content addSubview:panel];
    [panel addSubview:label];

    NSMutableArray *constraints = [NSMutableArray new];
    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[content]|"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:NSDictionaryOfVariableBindings(content)]];
    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[panel]|"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:NSDictionaryOfVariableBindings(panel)]];
    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[label]|"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:NSDictionaryOfVariableBindings(label)]];

    [self.view addConstraints:constraints]
    self.storedConstraints = constraints;

    [super updateViewConstraints];
}

- (void)invalidateConstraints
{
    [self.view removeConstraints:self.storedConstraints];
    [self.view needsUpdateConstraints];
}

0 个答案:

没有答案