UISearchController iOS 11 Customization

后端 未结 9 1220
南旧
南旧 2021-01-29 21:40

I had been using the following code prior to iOS 11 to customize the appearance of the UISearchController search bar:

var searchController = UISearc         


        
9条回答
  •  北荒
    北荒 (楼主)
    2021-01-29 22:28

    I just found out how to set them: (with some help of Brandon and Krunal, thanks!)

    The "Cancel" text:

    searchController.searchBar.tintColor = .white
    

    The search icon:

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

    The clear icon:

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

    The search text:

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

    The placeholder:

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

    The white background:

    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
    }
    

    Taken from here.

提交回复
热议问题