【问题标题】:how to set leading and trailing constraint for a xib used as titleView如何为用作 titleView 的 xib 设置前导和尾随约束
【发布时间】:2020-06-17 15:04:24
【问题描述】:

我有带有左右两个标签的 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

【问题讨论】:

    标签: swift constraints uinavigationbar titleview


    【解决方案1】:

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

    这是一个例子;标题视图的宽度限制分别为 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
    

    【讨论】:

    • 但是,宽度应该是动态的吧? with 是实现这一目标的正确方法吗?
    • 我的意思是它不是动态的。它是完全独立的;它不知道周围的环境。
    • 我明白了,你觉得计算窗口的宽度怎么样?
    • 当然,只要记住你基本上是在猜测。 :) 试一试,看看你是否能得到满意的结果。当然,如果我们轮换,您将不得不应付这个问题,但让我们稍后再过那座桥。
    • 当然,这样做了 - 请记住,这只是一个概念证明,但它确实证明了这个概念
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2015-04-02
    • 2021-09-23
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    相关资源
    最近更新 更多