Search code examples
iosautolayoutvisual-format-language

In AutoLayout can you combine both horizontal and vertical constraints using the Visual Format Language?


In our code in a lot of places, I keep seeing this...

containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":childView]))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":childView]))

It just seems redundant to me. I'm wondering if there's a way to combine the formats into a single string; something like this...

containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|;V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":childView]))

So is something like this possible?


Solution

  • For sorry you can't use this , but you can try something like this

    let rr = UIView()
    
    rr.backgroundColor = UIColor.red
    
    self.view.addSubview(rr)
    
    rr.translatesAutoresizingMaskIntoConstraints = false
    
    ["H:|-100-[rr]-100-|","V:|-100-[rr]-100-|"].forEach{NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: $0, options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["rr":rr]))}