gpt4 book ai didi

ios - 在约束依赖于框架的自定义 View 中使用自动布局

转载 作者:可可西里 更新时间:2023-11-01 03:33:47 26 4
gpt4 key购买 nike

我正在编写一个以编程方式初始化的自定义 View 。我重写 updateConstraints 以添加此 View 所需的所有约束。 :

- (void)updateConstraints {
[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];

[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];

// some more constraints, you get the point

self.bottomSpacingConstraint = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:-(0.2 * CGRectGetHeight(self.bounds))];
[self addConstraint:self.bottomSpacingConstraint];

[super updateConstraints];
}

问题是 self.bounds 返回了 CGRectZero 的等价物。我做了我的研究,并根据这个 objc.io article ,这是预期的,因为在调用 layoutSubviews 之前不会设置框架。它还提到

To force the system to update the layout of a view tree immediately, you can call layoutIfNeeded/layoutSubtreeIfNeeded (on iOS and OS X respectively). This can be helpful if your next steps rely on the views’ frame being up to date.

但是,当我添加

[self setNeedsLayout];
[self layoutIfNeeded];

就在 updateConstraints 中设置 self.bottomSpacingConstraint 之前,我仍然为框架返回一个 CGRectZero。根据 objc.io 文章(和这篇 SO answer),这些方法应该触发布局并更新框架。

任何人都可以阐明如何使这一切有效吗?我对解决方案以及导致调用哪些与布局相关的方法的解释感兴趣(例如,似乎更改 layoutSubviews 中现有约束的常量会导致 setNeedsUpdateConstraints 被调用,然后触发 updateConstraints 并导致多次添加约束。

最佳答案

我很确定您不能或不应该从 updateConstraints 调用 layoutIfNeeded。更新约束在布局周期的较早部分,因此我认为它不会产生您想要的效果。

在您的情况下,解决方案是检查 layoutSubviews 中依赖于框架的约束的 constant 属性,如果需要更新,则在那里更新或调用 setNeedsUpdateConstraints(小心引起循环)。

您说过更新约束会触发对 updateConstraints 的另一个调用 - 这是真的,我认为您滥用了 updateConstraints - 它用于更新 基于 View 内容更改的约束。如果它们尚不存在,您应该只添加这些约束。

关于ios - 在约束依赖于框架的自定义 View 中使用自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21265373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com