0

I read a couple of stack overflow entries to change a searchBar's placeholder text-attributes. However, in iOS13, none of them really work.

I wonder how the font, font-size and font-color of a searchBar Placeholder can be changed under iOS13 ?

Here is what I tried:

let myAttributes = [NSAttributedString.Key.font: UIFont(name: "Avenir-Heavy", size: 28) as Any]

navigationItem.searchController?.searchBar.placeholder = 
NSAttributedString(string: "placeholder text", attributes: myAttributes).string
iKK
  • 6,394
  • 10
  • 58
  • 131

2 Answers2

2

Swift 5:

 if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
                let atrString = NSAttributedString(string: "Search",
                                                   attributes: [.foregroundColor : color,
                                                                .font : UIFont.systemFont(ofSize: 10, weight: .bold)])
                textfield.attributedPlaceholder = atrString

            }
David
  • 71
  • 3
  • 1
    works nicely for iOS13.1. What is somewhat confusing is that Apple kicked out many `.value(forKey: ...)`fields - but obviously not for this case...! Again thanks ! – iKK Oct 15 '19 at 11:51
1

You can use this method without accessing the value for key since searchbar has searchTextField property. Add this code after initialising your searchbar.

let placeholder = NSAttributedString(string: "your placeholder text", attributes: [.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont(name: "Helvetica", size: 15)!])
searchBar.searchTextField.attributedPlaceholder = placeholder
Arun Kumar
  • 454
  • 9
  • 19