以编程方式创建的 UIView 的中心 X 到另一个 UIView - Objective C
Center X of a programmatically created UIView to another UIView - Objective C
为了尝试一下,我以编程方式创建了一个按钮,如下所示
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 置于新添加的按钮的中心,而不是相反。我在这里错过了什么?
您可能需要对按钮和标签执行此操作:
[button setTranslatesAutoresizingMaskIntoConstraints:FALSE];
[_testlabel setTranslatesAutoresizingMaskIntoConstraints:FALSE];
然后使用 AutoLayout 约束格式化语言添加额外的调整大小约束:
[self.view addConstraints: ... constraintsWithVisualFormat ...];
and/or 还使用更多
[self.view addConstraint: ... constraintWithItem ...]
为了尝试一下,我以编程方式创建了一个按钮,如下所示
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 置于新添加的按钮的中心,而不是相反。我在这里错过了什么?
您可能需要对按钮和标签执行此操作:
[button setTranslatesAutoresizingMaskIntoConstraints:FALSE];
[_testlabel setTranslatesAutoresizingMaskIntoConstraints:FALSE];
然后使用 AutoLayout 约束格式化语言添加额外的调整大小约束:
[self.view addConstraints: ... constraintsWithVisualFormat ...];
and/or 还使用更多
[self.view addConstraint: ... constraintWithItem ...]