【发布时间】:2020-10-13 19:20:53
【问题描述】:
编辑:我通过将标签添加为 titleView 的子视图来实现我想要的,但这并不完美。我将标签的底部锚点约束到标题视图的顶部锚点。我还用标题视图的中心 x 锚点约束了标签的中心 x 锚点。尽管如此,它看起来仍然略微偏离中心。此外,在非缺口设备上,标签在横向中不可见。
我有一个UILabel 我想将UITextField 设置为我的应用导航栏的titleView 上方或下方(最好是上方)。我尝试将标签的顶部锚点锚定到文本字段的底部锚点,就像这样,
titleLabel.topAnchor.constraint(equalTo: self.addressBar.bottomAnchor)
(这是在NSLayoutConstraint.activate里面)
但是当我尝试执行此操作时会在运行时崩溃。
*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x600003c84680 "UILabel:0x7fe7f8421970.top"> and <NSLayoutYAxisAnchor:0x600003c846c0 "UITextField:0x7fe7f842f700.bottom"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'
目前,我将标签的顶部锚点锚定到 topLayoutGuide 的底部锚点。这会将标签放在导航栏下方,这并不理想。 UI 完全用 Swift 代码完成,没有 IB。标签和文本字段的创建都是在 loadView 方法中完成的,以及约束。
这是我的 loadView 方法中的相关代码:
addressBar = UITextField(frame: CGRect(x: 0, y:0, width: (self.navigationController?.navigationBar.frame.size.width)!, height: 30))
navigationItem.titleView = addressBar
titleLabel = UILabel(frame: .zero)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(titleLabel)
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor),
// titleLabel.topAnchor.constraint(equalTo: self.addressBar.bottomAnchor),
titleLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
// More constraints...
])
文本字段和标签的其他属性稍后在viewDidLoad方法中设置。
这是我的第一个真正的应用程序,我完全用代码完成了 UI,所以这对我来说仍然是新的。我过去一直使用IB。我尝试对此进行研究,但我无法准确找到我想要做的事情。对此的任何帮助将不胜感激。如果您需要更多信息,请告诉我。
【问题讨论】:
-
titleLabel.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: "你想要的距离"),你要加下导航栏吗?
标签: ios swift constraints uilabel uinavigationbar