OGeek|极客世界-中国程序员成长平台

标题: iOS 11 在导航栏中自定义搜索栏 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:02
标题: 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 中这种“自动样式”的要点。感谢任何帮助。



Best Answer-推荐答案


我刚刚发现了如何设置它们的其余部分在 Brandon 的帮助下,谢谢!)

“取消”文本:

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

白色背景:

let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self

let searchBar = searchController.searchBar
searchBar.tintColor = UIColor.white
searchBar.barTintColor = UIColor.white

if let textfield = searchBar.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 = searchController
navigationItem.hidesSearchBarWhenScrolling = false

enter image description here

取自 here .

关于iOS 11 在导航栏中自定义搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46861355/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4