2

我在下面有这段代码,它配置了视图的约束:

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 未对齐,知道我能做什么吗?即使我通过约束将其设置为具有较高的高度值,中心也会偏移。

4

1 回答 1

0

您可能设置了 UINavigationBar 的委托和 UISearchBar 的委托,两者都 extends UIBarPositioningDelegate,所以您需要这样做:

extension ViewController: UINavigationBarDelegate {
  func position(for bar: UIBarPositioning) -> UIBarPosition {
    if bar is UINavigationBar {
      return .topAttached
    }
    return .any
  }
}

这只会应用.topAttached.UINavigationBar

于 2019-10-14T13:25:42.477 回答