如何为用作 titleView 的 xib 设置前导和尾随约束

how to set leading and trailing constraint for a xib used as titleView

我的 Xib 文件有两个标签,左边和右边。左边的前导为 0,右边的 0 为尾随。在 >= 15 约束之间。此视图用作导航栏中的标题视图。我的问题是:如何设置此 xib 以使左侧标签靠近 leftItem,右侧标签靠近 rightItem?

如何调用 xib

headerVC = HeaderViewController(nibName: "HeaderViewController", bundle: nil)

xib 是如何填充的

    navigationItem.titleView = headerVC?.view
                headerVC?.lbl1.text = name
                headerVC?.lbl2.text = balance

//test purpose
                    //        headerVC?.backgroundColor = .red
                    //this try of mine not working
                    let leftWidth = self.navigationItem.leftBarButtonItem?.width ?? 0.0
        let rightWidth = self.navigationItem.rightBarButtonItem?.width ?? 0.0
        let sides = leftWidth + rightWidth
        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width
//        NSLayoutConstraint.activate([
//            headerVC?.view.width = screenWidth - leftWidth - rightWidth
        headerVC?.view.widthAnchor.constraint(equalToConstant: screenWidth - sides).isActive = true
//        ])

解决方案,与下面的答案和this答案相关

        headerVC?.backgroundColor = .red
        headerVC?.view.translatesAutoresizingMaskIntoConstraints = false
        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width
        headerVC?.view.widthAnchor.constraint(equalToConstant: screenWidth * 0.75).isActive = true

您的约束将标题视图配置为尽可能小,同时仍显示标签。如果您希望标题视图更宽,则必须添加宽度约束以使其更宽。标题视图不能以任何方式"see"导航栏中的左右项目;您只需要自己弄清楚宽度应该是多少,然后进行设置即可。

举个例子;标题视图的宽度约束分别为 100 和 250。

例如第二个是

let v = UIView()
v.backgroundColor = .red
v.translatesAutoresizingMaskIntoConstraints = false
v.widthAnchor.constraint(equalToConstant: 250).isActive = true
v.heightAnchor.constraint(equalToConstant: 20).isActive = true
self.navigationItem.titleView = v