答案 0 :(得分:1)
尝试这样的事情:
//Individual button Width
self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 0.25, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: button2, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 0.25, constant: 0))
//Button1 left spacing
self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: self.view.frame.size.width * 0.15))
//Button2 Right Spacing
self.view.addConstraint(NSLayoutConstraint(item: button2, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -self.view.frame.size.width * 0.15))
//Y placement
self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: button2, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
此外,您将需要重置旋转约束,因为self.view.frame.size.width将更改。它已被用于计算约束常数。
答案 1 :(得分:0)
如果您不想重置约束,可以尝试制作这样的间距约束:
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: button1, attribute: NSLayoutAttribute.CenterX, multiplier: 0.275, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: button2, attribute: NSLayoutAttribute.CenterX, multiplier: 0.625, constant: 0))
请注意,视图的顺序是相反的。
我已经成功地将它用于IB,应该使用代码。