Changing Search Bar placeholder text font in Swift
27,638
Solution 1
//SearchBar Text
let textFieldInsideUISearchBar = dashBoardSearchBar.valueForKey("searchField") as? UITextField
textFieldInsideUISearchBar?.textColor = UIColor.whiteColor()
//SearchBar Placeholder
let textFieldInsideUISearchBarLabel = textFieldInsideUISearchBar!.valueForKey("placeholderLabel") as? UILabel
textFieldInsideUISearchBarLabel?.textColor = UIColor.whiteColor()
Solution 2
Set placeholder text font size:
UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.systemFont(ofSize: 12)
set search text font size:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.systemFont(ofSize: 12)
Solution 3
This is the easiest practise for changing the Font or any other similar changes in the textfield of searchBar. I have been using XCode 8.4, Swift 3.x, iOS 10.x.
extension UISearchBar {
func change(textFont : UIFont?) {
for view : UIView in (self.subviews[0]).subviews {
if let textField = view as? UITextField {
textField.font = textFont
}
}
} }
The above code can be called directly where you make an IBOutlet of the searchBar...
@IBOutlet weak var searchBar: UISearchBar! {
didSet {
searchBar.change(textFont: GlobalConstants.Font.avenirBook14)
}
}
Solution 4
searchBar.searchTextField.font = UIFont(name: "Helvetica", size: 40)
Solution 5
There is even an easier way in Swift 5:
searchBar[keyPath: \.searchTextField].font = UIFont(...)
Author by
user3746428
Updated on July 23, 2022Comments
-
user3746428 almost 2 years
I am trying to change the font of the placeholder text in the search bar within my Search Display Controller. I was looking at some examples and I tried to implement them but as they are in Objective-C, I wasn't able to find any that I could get to work.
For example, I tried this one:
UITextField *textField = [[searchBar subviews] objectAtIndex:1]; [textField setFont:[UIFont fontWithName:@"Helvetica" size:40]];
But I was unable to get past
var textField: UITextField = UISearchBar
Any ideas?