swift - 约束冲突的问题

标签 swift autolayout nslayoutconstraint

我不确定我在这里缺少什么,我已经研究了几个小时,不断查看教程,但我仍然遇到约束冲突的问题。基本上我有一个按钮,在这个按钮上我想添加一个位于按钮中心且大小相同的新 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/

相关文章:

iOS - 取消约束动画

swift - 当我在 UITextField 中输入文本时,整个 View 的位置向上移动

ios - 如何将一个 Storyboard用于具有自动布局(ios 6 + ios 7)的 4"and 3.5"iphone 屏幕?

ios - 一起使用 Realm.io 和 RestKit 时的属性数据类型

ios - 自从 Lottie 3.0 更新以来,setAnimation 发生了变化吗?

swift - 在另一个 TableView 上调用 dismiss() 后刷新 TableView 数据

ios - Google Maps iOS 的位置标记信息窗口

ios - 简单自定义 UITableViewCell 的自动布局错误

ios - 我想移动指定自动布局的 View 的位置。 (ios 6,xcode 4.5)

iOS - 对不同的 iPad 尺寸使用相同的约束,只是缩放 View ?