ios - 自动布局和编程约束 : How to deal with updateConstraints firing multiple times?

标签 ios objective-c autolayout

当以编程方式创建布局时,我遵循 Apple 的建议:覆盖 -updateConstraints,添加自定义约束,并在 subview 添加到 View 后调用 -setNeedsUpdateConstraints。我的典型设置如下所示:

- (void)setupViews
{
    //Style View

    //Add gesture recognizers

    //Add Subviews


    [self setNeedsUpdateConstraints];
}

- (void)updateConstraints
{
    //Add custom constraints       

    [super updateConstraints];
}

问题

有些情况下 -updateConstraints 会被多次触发(例如,当一个 View 的 Controller 被呈现或通过动画推送时)。这里的问题是每个添加的约束都会被重新添加。当尝试按需更改添加的约束的常量时,这会成为一个严重的问题,因为有两个原始约束随后相互冲突。我想,即使您在创建约束后没有操纵它们,拥有双倍的约束看起来也不太好。

可能的解决方案

1 - 在 -updateConstraints 中应用之前删除所有影响 View 的约束:

 - (void)updateConstraints
    {   
        //Remove all constraints affecting view & subviews

        //Add custom constraints

        [super updateConstraints];       
    }

2 - 设置布局标志并在添加自定义约束之前对其进行检查:

- (void)updateConstraints
{
    if (self.didAddConstraints) {
        [super updateConstraints];
        return;
    }

    //Add custom constraints   

    self.didAddConstraints = YES;    

    [super updateConstraints];
}

3 - 不要担心约束加倍,每当需要更改常量时,只需在重新添加之前删除该约束。

3 - 我没想到的很棒的东西。


此处的最佳做法是什么?

最佳答案

简短回答:可能的解决方案编号 2。

随着布局变得更加复杂,移除并重新应用所有约束可能会变得代价高昂。此外,如果您的布局是有状态的,则会遇到更多问题。

双重约束非常低效,您永远无法知道 updateConstraints 可能会被调用多少次。

作为this blog post表明,使用标志是处理此问题的最简单、最有效的方法。我自己就是这样处理的。

作为旁注,您提到存在一种您还没有想到的很棒的方法。大多数时候,最简单的方法是最棒的方法。 :)

关于ios - 自动布局和编程约束 : How to deal with updateConstraints firing multiple times?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24613419/

相关文章:

ios - crash - 重击 @escaping @callee_guaranteed (@unowned CMTime)

objective-c - UIPrintInteractionController presentFromRect 问题

ios - 无法同时满足约束 - 添加 subview 时

ios - 是否可以创建从plist读取的对象的可变版本

iphone - 每日 UILocaleNotification 的问题

ios - 不同 iPhone 上的动画

ios - UIview 起始中心看似不正确。 (虚假视觉)

ios - UITableViewCell 被空数据源数组卡住

ios - 仅设备上的 RestSharp/MonoTouch 错误

ios - 即使启用了位置服务,(PHAsset 位置)也会为相机胶卷照片返回(null)