Search code examples
iosswiftconstraintsvisual-format-language

Different between "|" and [superview] in Visual Format Language?


Here is a example in github set view programly in the center of the superview.

constraints = NSLayoutConstraint.constraintsWithVisualFormat(
      "H:[superview]-(<=1)-[label]",
      options: NSLayoutFormatOptions.AlignAllCenterY,
      metrics: nil,
      views: ["superview":view, "label":label])

My question is ,while I replaced the "[superview]" with "|", like apple document explain, I guess they are equals. Actually they're not, and it will not work.

my code.

   constraints = NSLayoutConstraint.constraintsWithVisualFormat(
                    "H:|-(<=1)-[imageview]",
                    options: NSLayoutFormatOptions.AlignAllCenterY,
                    metrics: nil,
                    views: ["imageview":imageview])

is there anything wrong ,or a bug with VFL? apple document here


Solution

  • The original code uses a trick (or a hack).

    AlignAllCenterY was not meant to center views within the container. The options are there to specify the relative position of the subviews - for example, if you have 3 labels in the same container, you can make them all top aligned or center aligned between themselves - not with the container (implicitly specified by |).

    The trick is that when you specify the superview explicitly, the framework doesn't realize it a adds the constraints.

    The correct way to center a view in its container is the following:

    let centerX = NSLayoutConstraint(item: label, 
                                attribute: .CenterX, 
                                relatedBy: .Equal,
                                   toItem: view,
                                attribute: .CenterX, 
                               multiplier: 1.0,        
                                 constant: 0.0);
    view.addConstraint(centerX);
    
    let centerY = NSLayoutConstraint(item: label, 
                                attribute: .centerY, 
                                relatedBy: .Equal,
                                   toItem: view,
                                attribute: .centerY, 
                               multiplier: 1.0,        
                                 constant: 0.0);
    view.addConstraint(centerY);