【问题标题】:Center X of a programmatically created UIView to another UIView - Objective C以编程方式创建的 UIView 的中心 X 到另一个 UIView - Objective C
【发布时间】:2015-08-09 15:16:28
【问题描述】:

只是为了尝试一下,我以编程方式创建了一个按钮,如下所示

UIBUtton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"Button" forState:UIControlStateNormal];
[button sizeToFit];
[self.view insertSubview:button belowSubview:_testlabel];

我的视图中已经有一个名为 _testlabel 的现有标签。我正在使用自动布局,我想将我新添加的按钮的 X 居中到 _testlabel,我尽我所能尝试了下面的代码:

[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:_testlabel attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual toItem:button
attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];

我所能做的就是将_testlabel 的X 放在新添加的按钮上,而不是相反。我在这里错过了什么?

【问题讨论】:

  • 您确定要添加按钮作为_testLabel 的子视图吗?
  • 我没有将它添加为你看到的 _testlabel 的子视图,我将它添加到“下面”_testlabel
  • 该调用会将其置于视图层次结构的下方,而不是几何上。文档很烂!
  • 我知道,我用它把它放在视图层次结构的下面。这不是问题,看第二部分。我不是想把它放在它下面。

标签: ios objective-c uiview autolayout constraints


【解决方案1】:

您可能需要对按钮和标签执行此操作:

    [button setTranslatesAutoresizingMaskIntoConstraints:FALSE];
    [_testlabel setTranslatesAutoresizingMaskIntoConstraints:FALSE];

然后使用 AutoLayout 约束格式化语言添加额外的调整大小约束:

[self.view addConstraints: ... constraintsWithVisualFormat ...];

和/或还使用更多

[self.view addConstraint: ... constraintWithItem ...]

【讨论】:

  • 我不敢相信我错过了,我已经好几个小时了...非常感谢!
猜你喜欢
  • 2018-06-04
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多