繁体   English   中英

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

[英]Why when I made my constraint relative to the superview's bottom did it operate from the superview's top? And is it now right?

我有以下代码:

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)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM