Search code examples
iosswiftconstraintsios-autolayoutvisual-format-language

How to set Constraint using Visual Formate Language for xib file


I created xib file for custom navigation controller, in that xib file i have 3 UIButtons and 1 UILabel. At runtime i will assign this xib file as navigation controller. i need to set constraint using VFL(Visual Format Language) in ViewController.

   let tempView = Bundle.main.loadNibNamed("CustomNavigation", owner: self, options: nil)?.first as! CustomNavigationView
    self.view.addSubview(tempView)

    tempView.backgroundColor = UIColor.lightGray
    //tempView.frame = CGRect(x: 0, y: 0, width:width, height: 64)

    let backBtn = tempView.back as UIButton
    let naviTitle = tempView.naviTitle as UILabel
    let bell = tempView.bell as UIButton
    let order = tempView.order as UIButton

I need to set constraint for backBtn, naviTitle, bell, order. i set constraint like this

let views = ["backBtn": backBtn,
                 "naviTitle": naviTitle,
                 "order": order] as [String : AnyObject]

    let iconVerticalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "V:|-20-[backBtn(60)]",
       options: [],
        metrics: nil,
        views: views)
    allConstraints += iconVerticalConstraints



    let nameLabelVerticalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "V:|-23-[naviTitle]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += nameLabelVerticalConstraints



    let skipButtonVerticalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "V:|-20-[order]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += skipButtonVerticalConstraints



    let welcomeHorizontalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "H:|[backBtn]-5-[naviTitle]-5-[order]|",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += welcomeHorizontalConstraints


    let topRowHorizontalConstraints = NSLayoutConstraint.constraints(
        withVisualFormat: "H:|-15-[backBtn(60)]-[naviTitle]-[order]-15-|",
       options: [.alignAllCenterY],
        metrics: nil,
        views: views)
    allConstraints += topRowHorizontalConstraints


   NSLayoutConstraint.activate(allConstraints)

But it won't work


Solution

  • At first I guess you have to disable autoresizing mask

    backBtn.translatesAutoresizingMaskIntoConstraints = false
    naviTitle.translatesAutoresizingMaskIntoConstraints = false 
    bell.translatesAutoresizingMaskIntoConstraints = false
    order.translatesAutoresizingMaskIntoConstraints = false
    

    Then repair your constraints as those can't be satisfied at same time

    "H:|[backBtn]-5-[naviTitle]-5-[order]|"
    "H:|-15-[backBtn(60)]-[naviTitle]-[order]-15-|"
    

    Your backBtn distance from superview can't be 0 and 15 at the same time, same for rest of those constraints.