Search code examples
swiftvisual-format-language

Centering Horizontal in visual format language


I have 3 labels which I have placed against each other like in this picture:

enter image description here

However right now they are placed against the left side, I wan't them to be placed in the center horizontal. Here is the visual format code for their horizontal placing:

let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
            "H:|[label][label2][label3]|",
            options: [],
            metrics: nil,
            views: views)

However whatever I test I can't get them to center, any thoughts?


Solution

  • If you want to make it center horizontally/vertically both as i understand from the image you can make it like this:

    // Center horizontally
    var constraints = NSLayoutConstraint.constraintsWithVisualFormat(
        "V:[superview]-(<=1)-[label2]",
        options: NSLayoutFormatOptions.AlignAllCenterX,
        metrics: nil,
        views: ["superview":view,"label2":label2])
    
    view.addConstraints(constraints)
    
    // Center vertically
    constraints = NSLayoutConstraint.constraintsWithVisualFormat(
        "H:[superview]-(<=1)-[label1][label2][label3]",
        options: NSLayoutFormatOptions.AlignAllCenterY,
        metrics: nil,
        views: ["superview":view, "label1":label1,"label2":label2,"label3":label3])
    
    view.addConstraints(constraints)
    

    so it will be look like this: enter image description here