当固定在 UINavigationBar 下方时,UISearchBar 没有居中
UISearchBar not getting centered when pinned below a UINavigationBar
我在下面有配置视图约束的代码:
func configNavigationBarConstraints() {
navigationBar.autoPinEdge(toSuperviewEdge: .leading)
navigationBar.autoPinEdge(toSuperviewEdge: .trailing)
if #available(iOS 11.0, *) {
navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
return
}
navigationBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
func configSearchBarConstraints() {
searchBar.autoPinEdge(.top, to: .bottom, of: navigationBar)
// taskHistorySearchBar.autoPinEdge(.top, to: .bottom, of: navigationBar, withOffset: 6) //This is a solution but no ideal, the height diff varies by device
searchBar.autoPinEdge(toSuperviewEdge: .left)
searchBar.autoPinEdge(toSuperviewEdge: .right)
}
此视图的结果:
请注意,UISearchBar 未对齐,知道我能做什么吗?即使我通过约束将其设置为具有较高的高度值,中心也会偏移。
您可能设置了 UINavigationBar 的委托和 UISearchBar 的委托,两者都扩展了 UIBarPositioningDelegate
,因此您需要这样做:
extension ViewController: UINavigationBarDelegate {
func position(for bar: UIBarPositioning) -> UIBarPosition {
if bar is UINavigationBar {
return .topAttached
}
return .any
}
}
这只会应用 UINavigationBar
的 .topAttached
设置。
我在下面有配置视图约束的代码:
func configNavigationBarConstraints() {
navigationBar.autoPinEdge(toSuperviewEdge: .leading)
navigationBar.autoPinEdge(toSuperviewEdge: .trailing)
if #available(iOS 11.0, *) {
navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
return
}
navigationBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
func configSearchBarConstraints() {
searchBar.autoPinEdge(.top, to: .bottom, of: navigationBar)
// taskHistorySearchBar.autoPinEdge(.top, to: .bottom, of: navigationBar, withOffset: 6) //This is a solution but no ideal, the height diff varies by device
searchBar.autoPinEdge(toSuperviewEdge: .left)
searchBar.autoPinEdge(toSuperviewEdge: .right)
}
此视图的结果:
请注意,UISearchBar 未对齐,知道我能做什么吗?即使我通过约束将其设置为具有较高的高度值,中心也会偏移。
您可能设置了 UINavigationBar 的委托和 UISearchBar 的委托,两者都扩展了 UIBarPositioningDelegate
,因此您需要这样做:
extension ViewController: UINavigationBarDelegate {
func position(for bar: UIBarPositioning) -> UIBarPosition {
if bar is UINavigationBar {
return .topAttached
}
return .any
}
}
这只会应用 UINavigationBar
的 .topAttached
设置。