我应该在哪里放置代码来自定义 UISearchBar 中的取消按钮?

Where I should put code to customize Cancel button in UISearchBar?

我试图更改使用 UISearchController(iOS 8 及更高版本)实现的 UISearchBar 中的取消按钮颜色。这是我使用的代码:

if self.resultSearchController.active {
        for subView in self.resultSearchController.searchBar.subviews  {
            for subsubView in subView.subviews  {
                if subsubView.isKindOfClass(UIButton) {
                    subsubView.tintColor =  UIColor.whiteColor()
                }
            }
        }
    }

如果我将它粘贴到 viewDidLoad 中,它不起作用,因为我认为取消按钮仅在 SearchController 变为活动时初始化。

如果我在 viewDidLayoutSubviews 中粘贴代码一切正常,但我不确定它是正确的方法。

那么,我应该把这段代码放在 TableViewController 的什么地方?

此外,我不明白我如何在我的 TableViewController 中收到 SearchController 变为非活动状态的通知。换句话说,我应该把这样的代码放在哪里:

if self.resultSearchController.active == false {
   //Do something 
}

首先你应该插入委托方法:-

 class HomeViewController: UIViewController,UISearchResultsUpdating, UISearchBarDelegate {

  var searchController: UISearchController!

  override func viewDidLoad() {
    super.viewDidLoad()
    searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search here..."
    searchController.searchBar.delegate = self
    searchController.searchBar.sizeToFit()
    searchController.hidesNavigationBarDuringPresentation = true
    tableView.tableHeaderView = searchController.searchBar
    searchController.searchBar.tintColor =  UIColor.whiteColor()

}

 func searchBarTextDidBeginEditing(searchBar: UISearchBar) {

}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {

}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

}

func updateSearchResultsForSearchController(searchController: UISearchController) {

}


}

然后使用委托方法并更改取消按钮颜色和您想要的东西

您可以在 AppDelegatedidFinishLaunchWithOptions: 中试试这个。

UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).tintColor = UIColor.whiteColor()

PS:这是一种通用方法,会影响 UISearchBar 中的 UIBarButtonItem 整个应用程序。

Swift 4.2, 4.0+ 添加了答案here 可以自定义如下的自定义搜索栏,

您可以查看SearchBar class的用法。