我试图在AutoLayout中定义约束,这会在另一个视图发生变化时自动调整视图大小。
有两个视图并排,我希望只有通过简单地使左边的一个变薄(并且不直接改变右侧视图的宽度约束)来使右边的视图增长。 我是否可以通过巧妙地使用约束来解决这个问题。
无需动画更改。
这是应用程序中的所有代码:
class ViewController: UIViewController {
var view1 = UIView()
var view2 = UIView()
var h1Constraints: [AnyObject]?
var h2Constraints: [AnyObject]?
var v1Constraints: [AnyObject]?
var v2Constraints: [AnyObject]?
override func viewDidLoad() {
super.viewDidLoad()
// Boilerplate
view1.backgroundColor = UIColor.redColor()
view2.backgroundColor = UIColor.greenColor()
view2.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "grow"))
view1.setTranslatesAutoresizingMaskIntoConstraints(false)
view2.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(view1)
view.addSubview(view2)
// Constraints
let views = ["view1":view1, "view2": view2]
let metrics = ["halfScreenWidth":view.frame.size.width/2, "screenHeight":view.frame.size.height]
h1Constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[view1(>=halfScreenWidth)]->=0-|", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)
h2Constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|->=0-[view2(>=halfScreenWidth)]|", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)
v1Constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view1(screenHeight)]", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)
v2Constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view2(screenHeight)]", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)
view.addConstraints(h1Constraints!)
view.addConstraints(h2Constraints!)
view.addConstraints(v1Constraints!)
view.addConstraints(v2Constraints!)
}
@objc func grow() {
for var index = 0; index < h1Constraints?.count; ++index {
var constraint = h1Constraints![index] as! NSLayoutConstraint
if constraint.firstAttribute == .Width {
constraint.constant = 20
}
}
self.view.layoutIfNeeded()
}
}
我只是试图告诉布局引擎视图大于或等于屏幕宽度的一半,同时具有可调节余量(大于,或等于0)。
这样,当我将左侧视图的宽度更改为20时,我认为右侧视图会增长,因为它声明了一个&gt; =宽度。
这不起作用。当左侧收缩时,右侧保持原样。
可以通过自动布局实现这种关系吗?
修改
根据@ luk2302的回答,解决方案如下:
// Constraints
let views = ["view1":view1, "view2": view2]
let metrics = ["halfScreenWidth":view.frame.size.width/2, "screenHeight":view.frame.size.height]
h1Constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[view1(>=halfScreenWidth)][view2(>=halfScreenWidth)]|", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)
v1Constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view1(screenHeight)]", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)
v2Constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view2(screenHeight)]", options: NSLayoutFormatOptions(0), metrics: metrics, views: views)
view.addConstraints(h1Constraints!)
view.addConstraints(v1Constraints!)
view.addConstraints(v2Constraints!)
答案 0 :(得分:2)
是的,如果我正确理解您的要求,就可以实现。我建议使用以下约束:
然后你可以改变最后一个约束的常量值,一切都应该按照需要运行。
请注意,我从未尝试通过代码创建约束,只使用IB - 但这将是我在那里的方式。