pankaj pankaj - 6 months ago 107
iOS Question

Change the font size of UISearchBar

How can I change the font size of

UISearchBar
?

Edit:

Answer

for(int i =0; i<[searchbar.subviews count]; i++) {
if([[searchbar.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
[(UITextField*)[searchbar.subviews objectAtIndex:i] setFont:[UIFont fontWithName:@"Helvetica" size:12]];
}


Thanks

Pankaj

Answer

The UISearchBar has a UITextField inside, but there's no property to access it. So, there is no way for doing it in a standard way.

But there is a non-stardard way to workaround it. UISearchBar inherits from UIView, you can access it's subviews using [searchBar subviews]. If you print in the console it's subviews you will see that it have these views.

UISearchBarBackground, UISearchBarTextField.

So, to change the font size you will only need to do that

    UITextField *textField = [[searchBar subviews] objectAtIndex:1];
[textField setFont:[UIFont fontWithName:@"Helvetica" size:40]];

But, if the UISearchBar changes in the future and the textfield isn't in the position 1 anymore, your program will crash, so it's better to check through the subviews the position of the UITextField and then set the font size.