如何在 ios 中以编程方式添加约束

How to add constraints programmatically in ios

我在 ios 中以编程方式创建了我的 UI 元素。 iphone 一切都很好,但我的按钮被拉长了。

btnLogin=[[UIButton alloc] initWithFrame:CGRectMake(80, h-90, w-160, 40)]; 这就是我创建按钮的方式。我知道在界面生成器中我们可以使用自动布局。但是如何以编程方式向此按钮添加约束?

因为现在虽然左右边缘是固定的,但按钮宽度会根据屏幕大小而变化。我怎样才能避免根据设备拉伸元素,我还想管理按钮和父视图边框之间左右两侧的相同间隙。

我该怎么做?请帮我 谢谢

这就是你想要的

 UIButton * button = [[UIButton alloc] init];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];

NSDictionary * buttonDic = NSDictionaryOfVariableBindings(button);
button.translatesAutoresizingMaskIntoConstraints = NO;

NSArray * hConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-80-[button]-80-|"
                                                                 options:0
                                                                 metrics:nil
                                                                    views:buttonDic];
[self.view addConstraints:hConstraints];

NSArray * vConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[button(40)]-90-|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:buttonDic];
[self.view addConstraints:vConstraints];

截图 iphone6

iPhone6p

更新:

H:|-80-[button]-80-|,这会在水平方向创建约束,superview 的左右按钮保持为 80

"V:[button(40)]-90-|",这在Vertical创建约束,button高度保持40并且bottoms to superview bottoms保持90