HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 在约束依赖于框架的自定义视图中使用自动布局大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个以编程方式初始化的自定义视图.我重updateConsTraints以添加此视图所需的所有约束. :
- (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之前框架不会被设置.它也提到了

但是,当我添加

[self setNeedsLayout];
[self layoutIfNeeded];

updateConsTraints中设置self.bottomSpacingConsTraint之前,我仍然得到一个CGRectZero返回框架.根据objc.io@L_675_7@(和本SO answer),这些方法应该触发布局并更新框架.

任何人都可以对如何使这一切工作有所启发吗?我对解决方案感兴趣,并解释了导致调用布局相关方法的原因(例如,看起来在layoutSubviews中更改现有约束的常量会导致调用setNeedsupdateConsTraints,然后触发updateConsTraints并导致约束要多次添加).

解决方法

我很确定你不能或不应该从updateConsTraints调用layoutIfNeeded.更新约束是在布局周期的早期部分,所以我认为它不会产生你想要的效果.

你的情况下,解决方案是检查layoutSubviews中依赖于帧的约束的常量属性,如果需要更新,则在那里更新它或调用setNeedsupdateConsTraints(小心引起循环).

您已经说过更新约束会触发另一个updateConsTraints的调用 – 这是真的,我认为您正在滥用updateConsTraints – 它是根据视图内容的更改来更新约束.您应该只添加那些约束(如果它们尚不存在).

大佬总结

以上是大佬教程为你收集整理的ios – 在约束依赖于框架的自定义视图中使用自动布局全部内容,希望文章能够帮你解决ios – 在约束依赖于框架的自定义视图中使用自动布局所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。