Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Search Bar placeholder text colour in iOS 13

UI Search Bar

I'm trying to set colour for placeholder text inside UISearchbar. Right now I've following code. It doesn't set white colour to placeholder text on iOS 13. It works on iOS 12. It seems something is either broken or support has been removed in iOS 13?

I've searched a lot and tried few workarounds but doesn't work. I've also tried to set attributed text colour for textfield but that also doesn't change colour.

Is there a working solution for this?

class CustomSearchBar: UISearchBar {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.sizeToFit()

        // Search text colour change
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = UIColor.white

        // Search Placeholder text colour change
        let placeHolderText = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        placeHolderText?.textColor = UIColor.white // doesn't work
    }
}
like image 760
Raymond Avatar asked Oct 26 '19 18:10

Raymond


2 Answers

viewDidLoad is too early

Put the code in viewDidAppear, viewDidLoad is too early. Then your placeholder should change to white

searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Enter Search Here", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
like image 175
candyline Avatar answered Nov 20 '22 07:11

candyline


In viewDidAppear

if iOS is higher than 13.0, use searchBar.searchTextField.attributedPlaceholder.

if iOS is lower than 13.0, use searchBar.value(forKey: "searchField") to access searchTextField

var searchBar = UISearchBar()
override func viewDidAppear(_ animated: Bool) {
   super.viewDidAppear(animated)
   if #available(iOS 13.0, *) {
       searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Enter Search Here", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
   } else {
       if let searchField = searchBar.value(forKey: "searchField") as? UITextField {
           searchField.attributedPlaceholder = NSAttributedString(string: "Enter Search Here", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white2])
       }
   }
}
like image 45
Banghua Zhao Avatar answered Nov 20 '22 06:11

Banghua Zhao