iOS 11自定义导航栏中的搜索栏

我想在iOS 11搜索栏中嵌入导航栏时更改文本和图标的颜色.所以占位符文本,搜索文本和搜索图标.

enter image description here

if #available(iOS 11.0,*) {
    navigationController?.navigationBar.prefersLargeTitles = false
    let searchController = UISearchController(searchResultsController: nil)
    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = false

    searchController.searchBar.placeholder = "Suchen"
    searchController.searchBar.tintColor = .white
}

正如您在图像中看到的那样,文本在深蓝色背景上呈灰色,看起来很难看.我希望文字和图标至少是白色的. (改变蓝色背景颜色也行不通,见my other question)

唯一有效的方法是改变闪烁光标的颜色和“取消”按钮,这是通过.tintColor属性完成的.

似乎在iOS 10及以下版本中工作的解决方案在iOS 11中似乎不再起作用,因此请仅发布您在iOS 11中工作的解决方案.谢谢.

也许我错过了iOS 11中关于这种“自动样式”的观点.任何帮助都表示赞赏.

解决方法

我刚刚发现了如何设置其余部分:(在布兰登的帮助下,谢谢!)

“取消”文字:

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]

感谢@Brandon的帮助!

enter image description here

占位符:

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

enter image description here

白色背景:

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
}

enter image description here

摘自here.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...