Search code examples
iphoneiosxcodeios5

How do you change font in UISearchBar for iOS5?


I'm trying to change the font for all of my UISearchBar objects using the new "appearance" proxy for iOS5 with something like:

 [[UISearchBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor whiteColor], UITextAttributeTextColor, 
  [UIFont fontWithName:@"Trebuchet MS" size:0.0], UITextAttributeFont,
  nil]];

Every time I run this, I'm getting this error:

"2012-05-28 03:01:52.264 DirectDx_ClientApp[30039:15503] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIAppearance setTitleTextAttributes:]: unrecognized selector sent to instance 0x8460cf0' * First throw call stack: (0x1ea8022 0x3a4fcd6 0x1ea9cbd 0x1e0eed0 0x1e0ecb2 0x5e695 0x5dd78 0x217aa 0x789386 0x78a274 0x799183 0x799c38 0x78d634 0x203bef5 0x1e7c195 0x1de0ff2 0x1ddf8da 0x1dded84 0x1ddec9b 0x789c65 0x78b626 0x2164d 0x2895 0x1) terminate called throwing an exception"

The method above works perfectly well with UITabBar and UINavigationBar.

Any insights?

Thanks very much in advance.


Solution

  • Checkout the apple reference guide for uisearchbar, under customizing appearance you can see what methods are avialable to you for a uisearchbar. SetTitleAttributes is not possible for a uisearchbar and I can not see another method where you change the font of the uisearchbar by means of appearance.

    Trying to call a method that is not supported by an object, will always give you an error. In your case setTitleArtributes is supported by other classes but sadly enough not for the uisearchbar.

    There is a workaround.