我正在尝试制作一个视图,该视图将作为一种“面板”,附加到视图控制器的右侧。
也就是说,它绑定到父视图控制器的尾部,顶部和底部边距,静态宽度为300
但是,我似乎无法正确解决问题,我要么打破约束,要么做某件事xcode告诉我是非法的。
我究竟做错了什么?
这是控制器中的代码
let myView = UIView() view.backgroundColor = UIColor.redColor() self.view.addSubview(view) let topConstraint = NSLayoutConstraint(item: myView, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0) let trailingConstraint = NSLayoutConstraint(item: self.view, attribute: .TrailingMargin, relatedBy: .Equal, toItem: myView, attribute: .Trailing, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: self.bottomLayoutGuide, attribute: .Top, relatedBy: .Equal, toItem: myView, attribute: .Bottom, multiplier: 1, constant: 0) let widthConstraint = NSLayoutConstraint(item: myView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 300) self.view.addConstraints([trailingConstraint]) view.addConstraints([topConstraint, bottomConstraint, widthConstraint])
其实在你的代码的问题是,你没有设置translatesAutoresizingMaskIntoConstraints的myview到false,只要你想使用自动布局限制,那么你必须设置translatesAutoresizingMaskIntoConstraints一个以虚假的。另一个问题是您没有添加myviewself.view我已经更新了您的代码,并且根据您的约束,它的工作正常。
translatesAutoresizingMaskIntoConstraints
myview
false
将以下代码放入ViewController中。
let myView = UIView() myView.backgroundColor = UIColor.redColor() self.view.addSubview(myView) myView.translatesAutoresizingMaskIntoConstraints = false view.addConstraint(NSLayoutConstraint(item: myView, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: myView, attribute: .Bottom, relatedBy: .Equal, toItem: self.bottomLayoutGuide, attribute:.Top, multiplier: 1, constant: 20)) view.addConstraint(NSLayoutConstraint(item: myView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute,multiplier: 1, constant: 300)) view.addConstraint(NSLayoutConstraint(item: myView, attribute: .TrailingMargin, relatedBy: .Equal, toItem: view, attribute: .TrailingMargin, multiplier: 1, constant: 0))