iOS-查找视图的顶部约束? [英] iOS - Find top constraint for a view?

查看:94
本文介绍了iOS-查找视图的顶部约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在代码中查找视图的顶部约束. 最重要的约束添加在情节提要中,我不想使用IBOutlet.

I am trying to find the top constraint of the view in code. The top constraint is added in storyboard, and I don't want to use an IBOutlet.

在以下代码中记录firstAttribute的值似乎总是返回NSLayoutAttributeHeight类型的约束.知道如何在代码中可靠地找到视图的顶部约束吗?

Logging the value of the firstAttribute in the following code seems to always return a constraint of type NSLayoutAttributeHeight. Any idea how I could reliably find a top constraint of a view in code?

NSLayoutConstraint *topConstraint;

for (NSLayoutConstraint *constraint in self.constraints) {
    if (constraint.firstAttribute == NSLayoutAttributeTop) {
        topConstraint = constraint;
        break;
    }
}

推荐答案

而不是遍历self.constraints,而应遍历self.superview.constraints.

Instead of iterating through self.constraints, you should iterate through self.superview.constraints.

self.constraints仅包含仅与视图相关的约束(例如,高度和宽度约束).

The self.constraints only contain constraints related to just the view (e.g. height and width constraints).

这是一个看起来像这样的代码示例:

Here's a code example of what this might look like:

- (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;
}

这篇关于iOS-查找视图的顶部约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆