【问题标题】:Where I should put code to customize Cancel button in UISearchBar?我应该在哪里放置代码来自定义 UISearchBar 中的取消按钮?
【发布时间】:2016-01-21 17:28:49
【问题描述】:

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

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 变为 Active 时才会初始化。

如果我将代码粘贴到 viewDidLayoutSubviews 中,一切正常,但我不确定它是否正确。

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

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

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

【问题讨论】:

    标签: xcode swift uitableview uisearchbar uisearchcontroller


    【解决方案1】:

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

     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) {
    
    }
    
    
    }
    

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

    【讨论】:

    • 谢谢!这有帮助。我的问题是我忘记将 self 分配给 .searchBar.delegate
    【解决方案2】:

    你可以在AppDelegatedidFinishLaunchWithOptions:试试这个。

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

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

    【讨论】:

      【解决方案3】:

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

      您可以查看SearchBar类的使用情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-24
        • 1970-01-01
        • 2014-01-04
        • 1970-01-01
        相关资源
        最近更新 更多