我试图在代码中找到视图的顶级约束.
在故事板中添加了顶级约束,我不想使用IBOutlet.
在故事板中添加了顶级约束,我不想使用IBOutlet.
在以下代码中记录firstAttribute的值似乎总是返回NSLayoutAttributeHeight类型的约束.任何想法如何可靠地找到代码中的视图的顶级约束?
- NSLayoutConstraint *topConstraint;
- for (NSLayoutConstraint *constraint in self.constraints) {
- if (constraint.firstAttribute == NSLayoutAttributeTop) {
- topConstraint = constraint;
- break;
- }
- }
解决方法
而不是迭代self.constraints,你应该遍历self.superview.constraints.
自我约束只包含与视图相关的限制(例如,高度和宽度约束).
这是一个代码示例:
- - (void)awakeFromNib
- {
- [super awakeFromNib];
- if (!self.topConstraint) {
- [self findTopConstraint];
- }
- }
- - (void)findTopConstraint
- {
- for (NSLayoutConstraint *constraint in self.superview.constraints) {
- if ([self isTopConstraint:constraint]) {
- self.topConstraint = constraint;
- break;
- }
- }
- }
- - (BOOL)isTopConstraint:(NSLayoutConstraint *)constraint
- {
- return [self firstItemMatchesTopConstraint:constraint] ||
- [self secondItemMatchesTopConstraint:constraint];
- }
- - (BOOL)firstItemMatchesTopConstraint:(NSLayoutConstraint *)constraint
- {
- return constraint.firstItem == self && constraint.firstAttribute == NSLayoutAttributeTop;
- }
- - (BOOL)secondItemMatchesTopConstraint:(NSLayoutConstraint *)constraint
- {
- return constraint.secondItem == self && constraint.secondAttribute == NSLayoutAttributeTop;
- }