Ios 以编程方式创建按钮约束
我已经使用故事板创建了“第一个按钮”,并为其设置了约束,现在我想以编程方式创建另一个按钮,并将其设置在第一个按钮上方,如下所示: 我用这段代码来实现这一点:Ios 以编程方式创建按钮约束,ios,objective-c,Ios,Objective C,我已经使用故事板创建了“第一个按钮”,并为其设置了约束,现在我想以编程方式创建另一个按钮,并将其设置在第一个按钮上方,如下所示: 我用这段代码来实现这一点: NSLayoutConstraint *xConstraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribut
NSLayoutConstraint *xConstraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
NSLayoutConstraint *Yxonstraints = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.invoiceTextField attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:200];
NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:200];
[self.view addConstraints:@[xConstraint,Yxonstraints,width,height]];
但是第二个按钮在中间和左边结束,也比它的实际大小小,我在这里做了什么错事?
NSLayoutConstraint *Yxonstraints = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.invoiceTextField attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
你不会想要的。您希望secondButton.top与firstButton.bottom之间留有空间:
NSLayoutConstraint *Yxonstraints = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.invoiceTextField attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20];
你需要
self.secondBu.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.secondBu.bottomAnchor.constraint(equalTo: self.firstBu.topAnchor, constant:-15)
self.secondBu.leadingAnchor.constraint(equalTo: self.firstBu.leadingAnchor),
self.secondBu.trailingAnchor.constraint(equalTo: self.firstBu.trailingAnchor),
self.secondBu.heightAnchor.constraint(equalTo: self.firstBu.heightAnchor)
])
但最简单的方法是在故事板的UIStackView
中插入firstBu,然后使用一行
self.stackView.insertArrangedSubview(secondBu,at:0)
您也可以在IB中将stackView spacing属性设置为15,也可以避免使用Apple推荐的
addConstraints
,并使用NSLayoutConstraint。激活[button.bottomAnchor constraintEqualToAnchor:self.checkoutBtn.topAnchor常量:-15];这是否与objective-c相同?