UISearchController 搜索栏未填满全宽

UISearchController's searchBar doesn't fill full width

编辑:我正在使用自动布局。

我在使用 UISearchController 的搜索栏填充整个屏幕宽度时遇到问题。我的设置是这样的:

  1. 我有一个 UIViewController。在里面,我把所有的元素都分开了。有一个显示结果的 UITableView。
  2. 由于我在 searchBar 与状态栏重叠时遇到了问题,因此我创建了一个具有约束的普通 UIView,以便它位于状态栏下方并填充 UIViewController 的整个宽度。这是我在这里看到过无数次的方法。
  3. 最后,我创建了 UISearchController 并将其添加为 "wrapperView"
  4. 的子视图

这是结果:

The blue is only to see to where the container view extends

对我来说,searchBar 要么没有正确填充容器,要么没有正确居中,因为左侧似乎没有另一侧那么宽。

此外,当搜索框处于活动状态时,一切都显示得很好,如下所示:

The table also displays fine

这是我进行设置的代码:

//Mark: - Outlets
@IBOutlet weak var wrapperView: UIView!
@IBOutlet weak var tableView: UITableView!

//Mark: - Properties
let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    /*!
    Sets the values of the searchController and it's behaviour
    */
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.delegate = self

    /*!
    Sets the values and behaviours of the tableView
    */
    tableView.delegate = self
    tableView.dataSource = self
    tableView.hidden = true

    definesPresentationContext = true
    searchController.searchBar.sizeToFit()
    searchController.searchBar.frame.size.width = self.view.frame.size.width
}

此外,我的搜索逻辑工作正常。

显然只有模拟器的搜索栏显示不佳。我不知道这是否是模拟器的错误,但在设备上它工作正常!因此,我将此答案标记为正确答案,希望它能为其他人提供良好的参考!干杯!