Updated 31 July 2019
Please find the steps to customise the UISearchBar as given below:
UISearchBar contains the UITextField which can be identified through key “searchField”.
Therefore we can access the UITextField through the key and perform necessary changes with it.
Change Search Bar Background Color
1 2 3 4 |
@IBOutlet weak var searchBar: UISearchBar! if let textfield = searchBar.value(forKey: "searchField") as? UITextField { textfield.backgroundColor = UIColor.red } |
Change Search Bar Text Color
1 2 3 4 |
@IBOutlet weak var searchBar: UISearchBar! if let textfield = searchBar.value(forKey: "searchField") as? UITextField { textfield.textColor = UIColor.white } |
Change Search Bar Placeholder Color
1 2 3 4 |
@IBOutlet weak var searchBar: UISearchBar! if let textfield = searchBar.value(forKey: "searchField") as? UITextField { textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]) } |
Change Search Bar Default Image Color
The left hand default search image in UISearchBar represents the left view of the UITextField.
The Image is rendered to change it to the desired colour.
1 2 3 4 5 6 7 |
@IBOutlet weak var searchBar: UISearchBar! if let textfield = searchBar.value(forKey: "searchField") as? UITextField { if let leftView = textfield.leftView as? UIImageView { leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate) leftView.tintColor = UIColor.red } } |
Hope it will help you in customising the UISearchBar in your app.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
2 comments