为什么 UISearchBar 在 Swift 中跳下并覆盖/重叠第一行?

Why UISearchBar jumps down and first row covered/ overlapped in Swift?

我在 UINavigationController 中添加 UISearchBar 作为 subView,但 subView 的行为很奇怪。它隐藏了 UITableView 的部分标题,当我点击它时它会跳到垂直居中。

以及如何将 UISearchBar 的背景颜色更改为橙​​色?我尝试了色调颜色和背景颜色,但没有用。

var searchController: UISearchController!
var searchResultController: UITableViewController!

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.isTranslucent = false

    navigationController?.navigationBar.prefersLargeTitles = true;
    navigationController?.navigationBar.largeTitleTextAttributes = [
        NSAttributedStringKey.foregroundColor : UIColor.white
    ]
    navigationController?.navigationBar.barTintColor = UIColor.orange

    searchController = UISearchController(searchResultsController: searchResultController)

    self.searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    self.definesPresentationContext = true

    let searchBar = searchController.searchBar
    searchBar.searchBarStyle = .default
    searchBar.tintColor = UIColor.orange
    searchBar.backgroundColor = UIColor.orange

    view.addSubview(searchBar)
}

我添加了以下行以隐藏详细信息中的搜索栏 ViewController 但它导致搜索栏向下跳转。

self.definesPresentationContext = true

我删除了该行,但我有关于详细信息的搜索栏 ViewController,这就是我修复它的方法。

我将搜索栏变量传递给详细视图控制器并将其 属性 设置为隐藏。我还添加了以下代码行,以便在用户 returns 返回原始视图时恢复搜索栏。

override func viewWillDisappear(_ animated: Bool) {
    searchBar.isHidden = false
}

以下代码行解决了第二个问题,即隐藏 table 视图的第一行或部分标题。

self.tableView.contentInset = UIEdgeInsetsMake(50,0,0,0);

试试下面的代码片段。

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        tableView.invalidateIntrinsicContentSize()
    }