I've been trying search results for hours, but I can't get this figured out. Perhaps it isn't possible. I'm trying to change the tint color of the placeholder text and magnifying glass of a UISearchBar. I'm only targeting iOS 8.0+ if that matters. Here's my code and what it looks like now:
let searchBar = UISearchBar()
searchBar.placeholder = "Search"
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.tintColor = UIColor.whiteColor()
I'd like for the search and magnifying glass to be white, or perhaps a dark green.
Made an Apple Swift version 4.1 search bar extension :-
import Foundation import UIKit extension UISearchBar{ func setTextField(placeHolderColor:UIColor = .gray,placeHolder:String = "Search Something",textColor:UIColor = .white,backgroundColor:UIColor = .black, placeHolderFont:UIFont = UIFont.systemFont(ofSize: 12.0), textFont:UIFont = UIFont.systemFont(ofSize: 12.0) ){ for item in self.subviews{ for mainView in (item as UIView).subviews{ mainView.backgroundColor = backgroundColor if mainView is UITextField{ let textField = mainView as? UITextField if let _textF = textField{ _textF.text = "success" _textF.textColor = textColor _textF.font = textFont _textF.attributedPlaceholder = NSMutableAttributedString.init(string: placeHolder, attributes: [NSAttributedStringKey.foregroundColor : placeHolderColor, NSAttributedStringKey.font : placeHolderFont]) } } } } } }
Then you can use this for your searchBar like this :-
controller.searchBar.setTextField(placeHolderColor: .white, placeHolder: "Search A Pet", textColor: .white, backgroundColor: .green, placeHolderFont: UIFont.systemFont(ofSize: 14.0), textFont: UIFont.systemFont(ofSize: 14.0))
Hope this contribution will work for my other friends :) Happy coding!!
Swift 4/xcode 9.0, Swift 3/xcode 8.2.1
UISearchBar customising sample
Usage
Result
In Swift 4, assuming your search controller is set like this:
then set placeholder text as follows:
I could not make it work properly with any of the above solutions.
I created the following UISearchBar category which works properly on iOS 8.4 and 10.3:
UISearchBar+PlaceholderColor.h
UISearchBar+PlaceholderColor.m
USAGE:
IMPORTANT NOTE:
Make sure that you call setPlaceholderColor: AFTER your UISearchBar has been added to the view and has created its view hierarchy.
If you open your search bar programmatically, call it AFTER your becomeFirstResponder call, as such:
Otherwise, if you are leveraging UISearchBarDelegate:
Swift 3: If you want to change the placeholder, clearbutton and magnifier glass
You can change the color of the text without violating the private api rule: