Change the font style for the UISearchBar cancel button

I am trying to change the font of the UISearchBar cancel button to "OpenSans", but I cannot access any properties. I can only change the hue color of the UISearchBar, which changes the text color of the button "Cancel the search button" and the search bar "UITextField":

searchBar.tintColor = UIColor(red: 187.0/255.0, green: 187.0/255.0, blue: 187.0/255.0, alpha: 1.0)

Is there any way to do this?

+4
source share
3 answers

Try something like this, it worked for me.

 UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont(name: "OpenSans", size: 15)!], forState: .Normal)

If you want to change the color, add it to your attribute array.

 NSForegroundColorAttributeName : UIColor.whiteColor()

Note. Made in iOS 9

+7
source

This is for Swift 3.0

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont(name: "OpenSans", size: 15)!], for: .normal)
+4
source

swift 2:

if #available(iOS 9.0, *) {
     UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(15, weight: UIFontWeightLight)], forState: .Normal)
} else {
     // Fallback on earlier versions
}

swift3:

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont(name: "OpenSans", size: 15)!], for: .normal)

Objective-C:

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                  [UIColor blueColor], 
                                                  UITextAttributeTextColor, 
                                                  [UIColor darkGrayColor], 
                                                  UITextAttributeTextShadowColor, 
                                                  [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], 
                                                  UITextAttributeTextShadowOffset,
                                                  nil] 
                                        forState:UIControlStateNormal];
0
source

All Articles