我为自定义导航控制器创建了 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)
但它不会工作