为什么当我相对于超级视图的底部进行约束时,它从超级视图的顶部运行?现在对吗?



我有以下代码:

self.noArticlesView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
UIImage *backgroundPattern = [UIImage imageNamed:@"no-articles-background.png"];
self.noArticlesView.backgroundColor = [UIColor colorWithPatternImage:backgroundPattern];
[self.view addSubview:self.noArticlesView];
UIImage *noArticlesImage = [UIImage imageNamed:@"no-articles-icon.png"];
UIImageView *noArticlesImageView = [[UIImageView alloc] initWithImage:noArticlesImage];
noArticlesImageView.translatesAutoresizingMaskIntoConstraints = NO;
[self.noArticlesView addSubview:noArticlesImageView];
NSLayoutConstraint *horizontalCenterConstraint = [NSLayoutConstraint constraintWithItem:noArticlesImageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.noArticlesView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
[self.noArticlesView addConstraint:horizontalCenterConstraint];
NSLayoutConstraint *verticalPlacementConstrant = [NSLayoutConstraint constraintWithItem:noArticlesImageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.noArticlesView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-230.0];
[self.noArticlesView addConstraint:verticalPlacementConstrant];

基本上,我在视图控制器的视图上添加一个视图(称为noArticlesView),该视图显示一条消息,表示当前没有添加内容(当然,在没有添加内容的情况下)。

然后,我在该视图中添加一个图像作为子视图,作为对此的指示。

但是,当我将图像的上述约束更改为具有属性toItem:self.view并将其添加到self.view而不是self.noArticlesView时,它会从视图的顶部而不是底部推动它(即,200作为常量将从顶部推动它200px)。

我通过设置图像相对于noArticlesView而不是self.view的约束来解决这个问题,但我仍然对这种行为感到好奇(我仍在学习自动布局,并想了解它)。


还有,我现在所做的正确吗?如果我想把它放在离底部230像素的位置,把常数设置为-230是正确的方法吗?将常量设置为负数是错误的形式还是其他什么?

我也经历过类似的奇怪事情,我怀疑这是因为超视图(在您的案例中为self.view)没有高度——它不会根据其超视图调整大小。这意味着self.view的底部等于顶部,使其看起来像是约束从顶部开始工作。你可以尝试两件事来验证这个理论:

  1. 检查self.view的框架(高度将为0)
  2. 设置self.view.clipsToBounds = YES(您的视图,包括背景视图,将不会显示,因为它们被剪裁)

这只是(或可能是)对正在发生的事情的解释,我不确定处理这件事的正确方法是什么。

至于你的另一个问题:这样做是完全有效的,尽管通常有更好的方法。问问自己"为什么是-230"?如果这是因为图像有230高,那么使用-noArticlesImage.size.height。如果230恰好是使整个视图看起来最好的数字,那么可以使用(尽管最佳实践要求使用常量或预处理器宏来定义230)。

最新更新