当前位置 : 主页 > 手机开发 > ios >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
我想在iOS 11搜索栏中嵌入导航栏时更改文本和图标的颜色.所以占位符文本,搜索文本和搜索图标. if #available(iOS 11.0, *) { navigationController?.navigationBar.prefersLargeTitles = false let searchController
我想在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.

网友评论