为了尝试一下,我以编程方式创建了一个 Button,如下所示
UIBUtton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"Button" forState:UIControlStateNormal];
[button sizeToFit];
[self.view insertSubview:button belowSubview:_testlabel];
我的 View 中已有一个名为 _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 置于新添加的按钮的中心,而不是相反。我在这里缺少什么?
最佳答案
您可能需要对按钮和标签都执行此操作:
[button setTranslatesAutoresizingMaskIntoConstraints:FALSE];
[_testlabel setTranslatesAutoresizingMaskIntoConstraints:FALSE];
然后使用 AutoLayout 约束格式化语言添加额外的调整大小约束:
[self.view addConstraints: ... constraintsWithVisualFormat ...];
和/或还使用更多
[self.view addConstraint: ... constraintWithItem ...]
关于ios - 以编程方式创建的 UIView 的中心 X 到另一个 UIView - Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905716/