1

我为自定义导航控制器创建了 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)

但它不会工作

4

1 回答 1

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,其余约束条件相同。

于 2016-12-08T16:17:40.217 回答