如何让 TableView 中的 SearchBar 看起来像设置应用程序中的搜索栏

How do I get a SearchBar in a TableView to look like the one in the Settings App

在我的应用程序中,我有一个可搜索的 TableView,顶部有一个 SearBar。我添加了 SearchBar,方法是通过 Interface Builder 将其拖入,然后将我的 TableView 设为 UISearchBarDelegate 并添加:

searchBar.delegate = self

结果如下

我想要的是我的 SearchBar 看起来像设置应用程序中的那个(每个 iOS 设备上预装的那个)看起来像这样

此外,当点击时,它的行为不同,因为它将视图的其余部分变灰并删除标题,如此处所示

而我的 SearchBar 仅在单击时打开键盘并显示光标。

我需要做什么才能实现这种特定的外观和感觉?

您可以通过创建它的子类来自定义 UISearchBar

class CustomSearchBar: UISearchBar {

    override init(frame:CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {

        self.placeholder = "Search"

        // Color of the text field (in your case it should be gray)
        self.barTintColor = yourGraySearchBarColor

        // Color of the cursor (you don't need to change this if you want to stay with the default blue)
        self.tintColor = UIColor.white

        // Background color of you search bar
        self.backgroundImage = UIImage(named: "SearchBarBG")
    }
}

要设置搜索栏的背景颜色,您必须创建一个图像,它是一个只有您想要的颜色的正方形(在您的情况下是浅灰色),大小无关紧要,我将其设置为 20x20像素。

你可以在整个屏幕上方添加一个semi-transparent灰色的UIView来使背景变暗(SearchBar除外,所以它需要在SearchBar下方)。如果你采用UISearchBarDelegate,你可以在searchBarTextDidBeginEditing(_ searchBar: UISearchBar)函数中添加这个叠加层,并在searchBarTextDidEndEditing(_ searchBar: UISearchBar)函数中移除它。

您可以通过编程方式将 UISearchController 添加到 navigationBar 来轻松完成此操作。使用代码创建 UISearchController :

let controller = UISearchController(searchResultsController: nil)

然后添加到navigationItem,

    controller.searchResultsUpdater = self
    controller.obscuresBackgroundDuringPresentation = false
    controller.searchBar.placeholder = "Search Candies"
    definesPresentationContext = true
    if #available(iOS 11.0, *) {
        navigationItem.searchController = controller
    } else {
        navigationItem.titleView = searchController.searchBar
    }

来源:https://www.raywenderlich.com/157864/uisearchcontroller-tutorial-getting-started