centerX
设置为父视图的centerX>。
IBOutletCollection(UIButton) NSArray *allButtons;
//3 buttons' references
IBOutletCollection(NSLayoutConstraint) NSArray *allButtonCenterConstraints;
//buttons' centerX constraints' references
然后如果在viewDidAppear:
中
int t = arc4random() %3;// one of the 3 cases you will need
if (t == 0) {//if you want all 3 buttons appears
//all buttons shown
NSLayoutConstraint *c1 = allButtonCenterConstraints[0];//first button's centerX reference.
NSLayoutConstraint *c2 = allButtonCenterConstraints[2];//third button's centerX reference.
c1.constant = -self.view.frame.size.width*0.25;//push left
c2.constant = +self.view.frame.size.width*0.25;//push right
}
else if (t == 1)
{
//two buttons shown;
[allButtons[0] setHidden:YES];// close the one you dont need
NSLayoutConstraint *c1 = allButtonCenterConstraints[1];
NSLayoutConstraint *c2 = allButtonCenterConstraints[2];
c1.constant = -self.view.frame.size.width*0.125;
c2.constant = +self.view.frame.size.width*0.125;
}
else
{
//close 2 buttons
[allButtons[0] setHidden:YES];
[allButtons[1] setHidden:YES];
}
[self.view layoutIfNeeded];
如果您需要根据按钮宽度设置某些内容,您可以根据按钮的宽度设置常量。
在以编程方式设置约束之后,创建约束插座
例如:
@IBOutlet var mainViewWidthConstant: NSLayoutConstraint!
if (self.view.frame.size.width == 320){
mainViewWidthConstant.constant = 320
}
else if (self.view.frame.size.width == 375)
{
mainViewWidthConstant.constant = 375
}
else{
mainViewWidthConstant.constant = 414
}