ios - 约束到 UINavigationController navigationBar anchor

标签 ios swift uinavigationcontroller constraints nslayoutconstraint

我试图将 View 限制为 100% 类似于 UINavigationControllernavigationBar。以下无效...

view.addSubview(someView)

someView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    someView.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor),
    someView.trailingAnchor.constraint(equalTo: navigationBar.trailingAnchor),
    someView.topAnchor.constraint(equalTo: navigationBar.topAnchor),
    someView.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor)
])

但将前三个约束中的任何替换为 view 会使 someView 可见。这例如有效:

NSLayoutConstraint.activate([
    someView.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor),
    someView.trailingAnchor.constraint(equalTo: navigationBar.trailingAnchor),
    someView.topAnchor.constraint(equalTo: view.topAnchor),
    someView.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor)
])

在另一侧的 UITabBarController 中约束到 tabBar 即使在将所有内容都约束到 tabBar 时也是如此:

NSLayoutConstraint.activate([
    someView.leadingAnchor.constraint(equalTo: tabBar.leadingAnchor),
    someView.trailingAnchor.constraint(equalTo: tabBar.trailingAnchor),
    someView.topAnchor.constraint(equalTo: tabBar.topAnchor),
    someView.bottomAnchor.constraint(equalTo: tabBar.bottomAnchor)
])

我对解决方法没问题,但我想知道为什么在单独约束 navigationBar 时它不起作用。有没有更好的方法使 someViewnavigationBar 具有相同的大小和位置?

最佳答案

如果您将 subview 添加为 view 的 subview ,并且仅对 navigationBar 设置约束,则它们没有共同的祖先,因为您会收到错误消息:

'Unable to activate constraint with anchors < NSLayoutXAxisAnchor:xxx "UIView:xxx.leading" > and < NSLayoutXAxisAnchor:xxx "UINavigationBar:xxx.leading" > because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'

... 看起来如果你设置至少一个约束等于 view,现在你的 someView 知道它与其父 View view 有一些共同点 以及 navigationBar

解决问题的一种方法是将 View 添加到 NavigationBar

navigationBar.addSubview(someView)

注意:我已经测试了你的代码,它不适用于设置等于 TabBar anchor 的约束

关于ios - 约束到 UINavigationController navigationBar anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803816/

相关文章:

javascript - 解析云代码作业:删除数据库中已有一个小时的行

swift - Swift 中的 JSON 解析

ios - 将字符串转换为数组字符

快速检查文本字段输入

ios - 显示页面时出现 UiNavigation 错误

iphone - 自定义以编程方式创建的导航栏的背景图像

ios - MFMailComposeViewController navigationBar 颜色不完全匹配

ios - 本地化为法语时,静态 UIView 更改宽度

ios - 静态 TableView 获取 NSRangeException

iphone - Objective-C 正则表达式