我试图将 View 限制为 100% 类似于 UINavigationController
的 navigationBar
。以下无效...
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
时它不起作用。有没有更好的方法使 someView
与 navigationBar
具有相同的大小和位置?
最佳答案
如果您将 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/