如何使用Visual Formate语言为xib文件

时间:2016-12-08 15:52:29

标签: ios swift constraints ios-autolayout visual-format-language

我为自定义导航控制器创建了xib文件,在该xib文件中我有3个UIButtons和1个UILabel。 在运行时,我将此xib文件指定为导航控制器。 我需要在ViewController中使用VFL(可视格式语言)设置约束。

   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

我需要为backBtn,naviTitle,bell,order设置约束。我设置像这样的约束

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)

但它不会工作

1 个答案:

答案 0 :(得分:0)

首先我想你必须禁用自动调整大小掩码

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

然后修复你的约束,因为那些不能同时满足

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

你与superview的backBtn距离不能同时为0和15,其余约束也是如此。