Search code examples
swiftautolayoutvisual-format-language

Convert Visual Format Language greater than to Constraint


How would I convert this into a constraint?

"V:|->=0-[contentView]->=0-|"

Would it look like this?

contentView.topAnchor.constraint(lessThanOrEqualTo: topAnchor, constant: 0.0)
contentView.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: 0.0)

Solution

  • Since you haven't specified which view is the superview of contentView, we'll have to use contentView.superview! for the containing view. Therefore, your visual format is equivalent to:

    contentView.topAnchor.constraint(greaterThanOrEqualTo: contentView.superview!.topAnchor, constant: 0.0)
    contentView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.superview!.bottomAnchor, constant: 0.0)
    

    Notes:

    1. If contentView has already been added as a subview of another view (which you should always do before creating constraints), then force unwrapping contentView.superview is safe.
    2. contentView will start lower on the screen than its superview and the coordinates grow in the downward direction, so its offset will be larger making the constraint greaterThanOrEqualTo the superview's topAnchor.
    3. Likewise, contentView will end above or touching its superview's bottomAnchor, so the constant in this case will be lessThanOrEqualTo 0.