在iOS 11之前,我一直在使用以下代码来自定义UISearchController搜索栏的外观:

var searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.setDefaultSearchBar()
searchController.searchResultsUpdater = self

if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
} else {
    tableView.tableHeaderView = searchController.searchBar
}

extension UISearchBar {
    func setDefaultSearchBar() {
        self.tintColor = UIColor.blue
        self.searchBarStyle = .minimal
        self.backgroundImage = UIImage(color: UIColor.clear)
        let searchBarTextField = self.value(forKey: "searchField") as! UITextField
        searchBarTextField.textColor = UIColor.white
        searchBarTextField.tintColor = UIColor.blue
        searchBarTextField = .dark
    }
}

但是,在iOS 11上运行相同代码时,搜索栏的外观无法更新。

iOS 10:

ios - UISearchController iOS 11自定义-LMLPHP

iOS 11:

ios - UISearchController iOS 11自定义-LMLPHP

到目前为止,对该问题的大部分关注都集中在搜索栏的文本颜色上。我所关注的不仅仅是背景颜色,色调颜色,搜索指示器,清除按钮颜色等。

最佳答案

我刚刚发现了如何设置它们:(在Brandon和Krunal的帮助下,谢谢!)

“取消”文本:

searchController.searchBar.tintColor = .white

搜索图标:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.search, state: .normal)

清除图标:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.clear, state: .normal)

搜索文字:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]

ios - UISearchController iOS 11自定义-LMLPHP

占位符:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

ios - UISearchController iOS 11自定义-LMLPHP

白色背景:
if #available(iOS 11.0, *) {
    let sc = UISearchController(searchResultsController: nil)
    sc.delegate = self
    let scb = sc.searchBar
    scb.tintColor = UIColor.white
    scb.barTintColor = UIColor.white

    if let textfield = scb.value(forKey: "searchField") as? UITextField {
        textfield.textColor = UIColor.blue
        if let backgroundview = textfield.subviews.first {

            // Background color
            backgroundview.backgroundColor = UIColor.white

            // Rounded corner
            backgroundview.layer.cornerRadius = 10;
            backgroundview.clipsToBounds = true;
        }
    }

    if let navigationbar = self.navigationController?.navigationBar {
        navigationbar.barTintColor = UIColor.blue
    }
    navigationItem.searchController = sc
    navigationItem.hidesSearchBarWhenScrolling = false
}

ios - UISearchController iOS 11自定义-LMLPHP

取自here

关于ios - UISearchController iOS 11自定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45663169/

10-12 00:08
查看更多