我不确定我在这里缺少什么,我已经研究了几个小时,不断查看教程,但我仍然遇到约束冲突的问题。基本上我有一个按钮,在这个按钮上我想添加一个位于按钮中心且大小相同的新 View 。当我去应用约束时,它告诉我存在冲突的约束,而我只是不明白这里可能发生冲突。
//Create a new view
let selectBorderView = UIView();
//Guarantee there are no constraints attached to it
NSLayoutConstraint.deactivateConstraints(selectBorderView.constraints);
//Add the new view to the button
sender.addSubview(selectBorderView);
//Create constraint selectBorderView.width = button.width
let constraintEW = NSLayoutConstraint(item: selectBorderView, attribute: .Width, relatedBy: .Equal, toItem: selectBorderView.superview, attribute: .Width, multiplier: 1, constant: 0);
//Create constraint selectBorderView.height = button.height
let constraintEH = NSLayoutConstraint(item: selectBorderView, attribute: .Height, relatedBy: .Equal, toItem: selectBorderView.superview, attribute: .Height, multiplier: 1, constant: 0);
//Create constraint selectBorderView.centerX = button.centerX
let constraintCX = NSLayoutConstraint(item: selectBorderView, attribute: .CenterX, relatedBy: .Equal, toItem: selectBorderView.superview!, attribute: .CenterX, multiplier: 1, constant: 0);
//Create constraint selectBorderView.centerY = button.centerY
let constraintCY = NSLayoutConstraint(item: selectBorderView, attribute: .CenterY, relatedBy: .Equal, toItem: selectBorderView.superview, attribute: .CenterY, multiplier: 1, constant: 0);
//add the constraints to the button
selectBorderView.superview!.addConstraint(constraintEW);
selectBorderView.superview!.addConstraint(constraintEH);
selectBorderView.superview!.addConstraint(constraintCX);
selectBorderView.superview!.addConstraint(constraintCY);
最佳答案
您可能会看到一条错误消息,内容如下:
Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
如果您看到该警告,则应设置 translatesAutoresizingMaskIntoConstraints
为假
:
selectBorderView.translatesAutoresizingMaskIntoConstraints = false
关于swift - 约束冲突的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35702730/