【问题标题】:Auto-layout on a View for a Navigation Bar's title导航栏标题的视图自动布局
【发布时间】:2019-01-04 04:54:23
【问题描述】:

我有一个简单的类,它创建一个包含标签的UIView。我想将该视图用作UINavigationBar 的中心部分,两侧各有2 个按钮。下面的代码在不添加标签的情况下运行良好:

class myView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = .green
    }
}

我这样称呼班级:

let avatar = UIBarButtonItem(image: avatarImage, ...)
let otherButton = UIBarButtonItem(image: otherImage, ...)

navigationItem.leftBarButtonItems  = [avatar]
navigationItem.rightBarButtonItems = [otherButton]

let headerTitle = myView(frame: .zero)
headerTitle.translatesAutoresizingMaskIntoConstraints = false
navigationItem.titleView = headerTitleView

但如果我在 UIView 中添加标签:

class myView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = .green

        let theLabel = UILabel(frame: .zero)
        theLabel.text = "The Title"
        theLabel.textAlignment = .center
        theLabel.translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(theLabel!)
    }
}

.. 我看到了标签,但它卡在视图的最左侧。如果我尝试向标签添加约束,如下所示:

NSLayoutConstraint.activate([
    theLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
    theLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor)
])

.. 它崩溃了,因为 self(UIView)的大小仍然是 .zero。

我尝试了layoutIfNeeded()sizeToFit() 的各种组合,但到目前为止都没有成功。如何将视图放置为导航栏的标题以及该视图内的布局元素?

【问题讨论】:

  • 嗨!您是否在设置标签文本后尝试调用 sizeToFit() ?当我尝试在导航栏中放置标签时,这对我有帮助
  • 是的@joliejuly,我在设置文本之后就输入了theLabel.sizeToFit();没有区别 - 仍然在左上角。
  • 什么崩溃............
  • @Sh_Khan: libc++abi.dylib: terminating with uncaught exception of type NSException(信号 SIGABRT)
  • 请暂时共享所有控制台日志

标签: ios swift uinavigationbar nslayoutconstraint


【解决方案1】:

我猜是订单错误

self.addSubview(theLabel) // first
NSLayoutConstraint.activate([  // then second
  theLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
  theLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor)
])

【讨论】:

    猜你喜欢
    • 2016-06-30
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2012-01-16
    • 1970-01-01
    • 2015-07-05
    相关资源
    最近更新 更多