How to change UISearchBar Font Size & Color?
To change text and placeholder searchbar:
// SearchBar text
let textFieldInsideUISearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideUISearchBar?.textColor = UIColor.red
textFieldInsideUISearchBar?.font = textFieldInsideUISearchBar?.font?.withSize(12)
// SearchBar placeholder
let labelInsideUISearchBar = textFieldInsideUISearchBar!.value(forKey: "placeholderLabel") as? UILabel
labelInsideUISearchBar?.textColor = UIColor.red
Here's how you can change the font and text color on latest Swift:
let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(15), NSAttributedString.Key.foregroundColor: UIColor.gray]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = attributes
In the iOS 13 or newest, the UISearchBar has a property called searchTextField
. But earlier, we can not use this property.
So, we can extend for UISearchBar:
extension UISearchBar {
var textField: UITextField? {
if #available(iOS 13.0, *) {
return self.searchTextField
} else {
// Fallback on earlier versions
for view in (self.subviews[0]).subviews {
if let textField = view as? UITextField {
return textField
}
}
}
return nil
}
}
And use:
searchBar.textField?.font = UIFont.systemFont(ofSize: 12)