我正在尝试自定义约束
菜单栏类:
import UIKit
class ManuBar: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.blueColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerate() {
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
}
View Controller :
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupManuBar();
}
let menuBar : ManuBar = {
let mb = ManuBar()
return mb
}()
private func setupManuBar(){
view.addSubview(menuBar)
view.addConstraintsWithFormat("H:|[v0]|",views : menuBar)
view.addConstraintsWithFormat("V:|-16-[v0(40)]|",views : menuBar)
}
}
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.
(
"<NSLayoutConstraint:0x7ff891d27c70 V:|-(16)-[Tab_Menu_Bar_Programmatically.ManuBar:0x7ff891d19f30] (Names: '|':UIView:0x7ff891d1b570 )>",
"<NSLayoutConstraint:0x7ff891d27f40 V:[Tab_Menu_Bar_Programmatically.ManuBar:0x7ff891d19f30(40)]>",
"<NSLayoutConstraint:0x7ff891d0fc50 V:[Tab_Menu_Bar_Programmatically.ManuBar:0x7ff891d19f30]-(0)-| (Names: '|':UIView:0x7ff891d1b570 )>",
"<NSLayoutConstraint:0x7ff891d1c8e0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7ff891d1b570(736)]>"
)
将尝试通过打破约束来恢复
如果您需要更多信息,请告诉我
最佳答案
您在 view.translatesAutoresizingMaskIntoConstraints = false
中忘记了 view,因此您是在单元格上而不是在各个 View 上设置 translatesAutoresizingMaskIntoConstraints。
将for循环改为
for (index, view) in views.enumerate(){
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionry[key] = view
}
我也会看看 lazy loading通过添加 lazy 关键字来查看 View 。
更新:
虽然您显着更改了代码。我测试了你的第一个例子,它成功了。您现在的问题是: view.addConstraintsWithFormat("V:|-16-[v0(40)]|",views : menuBar)
您基本上是将菜单栏的高度设置了两次。您将它设置为 40 的固定高度,但您还告诉它根据 superview 进行拉伸(stretch)。顶部 16 像素 空格 + 底部 0 像素。去掉末尾的|
像这样:
view.addConstraintsWithFormat("H:|[v0]|",views : menuBar)
view.addConstraintsWithFormat("V:|-16-[v0(40)]",views : menuBar)
关于ios - 如何解决Unable simultaneously satisfy constraints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39517149/