Sunday 4 June 2017

TextColor and backgroundColor Properties of UISearchBar

UISearchBar search text color

If we want to set the search text color in UISearchBar, we can do this either programmatically or in interface builder.

In order to change the text color in UISearchBar, we have to access the UITextField inside the UISearchBar. We can do this by using valueForKey("searchField")

var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField

textFieldInsideSearchBar?.textColor = yourcolor

To set the text color of UISearchBar in interface builder,  go to in identity inspector- > User Defined Runtime Attributes -> in Key Path add searchField.textColor  and in Type write Color and in value set color.

In swift we can also create an extension for UISearchBar

public extension UISearchBar {

   public func setTextColor(color: UIColor) {
       let svs = subviews.flatMap { $0.subviews }
       guard let tf = (svs.filter { $0 is UITextField }).first as? UITextField else { return }
       tf.textColor = color
   }
}

UISearchBar background color

If you want to set the background color of UISearchBar,  you can change it in your ViewController and don't want anywhere else to effect then use

for view in searchBar.subviews {
           for subview in view.subviews {
               if subview .isKindOfClass(UITextField) {
                   let textField: UITextField = subview as! UITextField
                   textField.backgroundColor = UIColor.redColor()
               }
           }
    }

But if you want it to be change in whole app and targeting the iOS 9.0 or later then should be using appearanceWhenContainedInInstancesOfClasses like

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.redColor()

No comments:

Post a Comment