OGeek|极客世界-中国程序员成长平台

标题: ios - 以编程方式创建的 UIView 的中心 X 到另一个 UIView - Objective C [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:49
标题: ios - 以编程方式创建的 UIView 的中心 X 到另一个 UIView - Objective C

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

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 放在新添加的按钮上,而不是相反。我在这里错过了什么?



Best Answer-推荐答案


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

    [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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4