【问题标题】:Autolayout not working as expected自动布局未按预期工作
【发布时间】:2014-07-01 05:51:14
【问题描述】:

我正在尝试使用 Autolayout 构建应用程序。使用故事板和编程方式尝试过,但没有运气。视图的行为与预期不符。

这是输出屏幕。 (针对iOS7)

问题:我希望绿色按钮位于红色按钮上方,垂直间距为 10 像素。但是红色按钮在 3.5 英寸显示器上重叠,在 4 英寸显示器上是正确的。

下面是我试过的代码。

        [self.btnGreen setTranslatesAutoresizingMaskIntoConstraints:NO];

        [self.viewContainer addConstraint:[NSLayoutConstraint constraintWithItem:self.btnGreen attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.viewContainer attribute:NSLayoutAttributeHeight multiplier:1.0 constant:100.0]];


        [self.viewContainer addConstraint:[NSLayoutConstraint constraintWithItem:self.btnGreen attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.viewContainer attribute:NSLayoutAttributeWidth multiplier:1.0 constant:100.0]];

我在以下链接中进行了裁判: 1)Apple guideline 2)http://matthewmorey.com/ 3)Also this one

但没有得到想要的输出。

任何帮助将不胜感激。

【问题讨论】:

  • 如果您只是将宽度或高度限制为常数,则无需指定第二项。您可以改为:[NSLayoutConstraint constraintWithItem:self.btnGreen attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute: NSLayoutAttributeNotAnAttribute multiplier:0 constant:width];
  • 看起来你的绿色按钮甚至不适合你的红色按钮和上面的白色框之间的间隙?您希望布局看起来如何?

标签: ios ios7 autolayout


【解决方案1】:

试试这些约束,如图:

【讨论】:

  • 感谢您的快速回复。但它现在工作。我得到了同样的行为。
  • 通过这样做,绿色视图与其上方的视图重叠。
  • 你应该添加从 TopView 到 superView 的垂直空间约束,常量为 170(btnGreenHeight + btnRedHeight + 间距)。
猜你喜欢
  • 1970-01-01
  • 2017-02-17
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多