Search code examples
swiftnslayoutconstraint

NSLayoutConstraint withVisualFormat layout


NSLayoutConstraint Hello, I've been trying to wrap my head arround NSLayoutConstraint withVisualFormat and I'm having a heck of a time. I have three lables and I want to order them in a specific format but I cant seem to get it. I'm doing this in a custom UITableViewCell.

I have tried to draw the cell layout below. How would I accomplist this?

--------------------------------------------------------------------------------
(10 padding)Name
                                                           ColorName(10 padding)
(10 padding)Description
--------------------------------------------------------------------------------

Solution

  • The trick is to use multiple visual constraints to arrange everything vertically and horizontally. You can combine all three views together into one vertical constraint because they're all lined up, but for the horizontal constraints, you'll need one for each row (so three total).

    You'll need to specify the heights of the elements in the visual constraint to have everything line up

    Here's some sample code:

    let name = UITextField(frame: CGRect())
    name.text = "Name"
    name.translatesAutoresizingMaskIntoConstraints = false
    name.backgroundColor = UIColor.red
    
    let colorName = UITextField(frame: CGRect())
    colorName.text = "ColorName"
    colorName.translatesAutoresizingMaskIntoConstraints = false
    colorName.backgroundColor = UIColor.gray
    
    let description = UITextField(frame: CGRect())
    description.text = "Description"
    description.translatesAutoresizingMaskIntoConstraints = false
    description.backgroundColor = UIColor.green
    
    view.addSubview(name)
    view.addSubview(colorName)
    view.addSubview(description)
    
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[name]", options: [], metrics: nil, views: ["name": name]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[colorName]-(10)-|", options: [], metrics: nil, views: ["colorName": colorName]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[description]", options: [], metrics: nil, views: ["description": description]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(50)-[name]-(10)-[colorName]-(10)-[description]", options: [], metrics: nil, views: ["name": name, "colorName": colorName, "description": description]))
    

    For the vertical constraint, I used a padding of 50 from the top, and 10 points between each object. Obviously, you can set these to whatever you want.