Search code examples
iosobjective-cuiappearance

UIAppearance - Toolbar & SearchBar crash


I'm getting the unrecognized selector sent to instance error while customizing the UIToolbar and the UISearchBar aspect via UIAppearance.

The weird thing is that crashed only on 6.1 or lower, on iOS7 is fine and it doesn't crash.

This is the code I'm using:

[[UIToolbar appearance] setBackgroundImage:[UIImage imageNamed:@"toolbarBackground"] forToolbarPosition:UIBarPositionBottom barMetrics:UIBarMetricsDefaultPrompt];
[[UIToolbar appearance] setTintColor:[UIColor whiteColor]];
[[UISearchBar appearance]setBackgroundImage:[UIImage imageNamed:@"searchBarBackground"]  forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
[[UISearchBar appearance] setTintColor:[UIColor whiteColor]];

and it should be fine. But everytime I launch the app on iOS 6.1 Simulator i get

-[_UIAppearance setBackgroundImage:forBarPosition:barMetrics:]: unrecognized selector sent to instance 0xaba4550

for both UIToolbar and UISearchBar. I'm sure they are causing the crash because if I comment the lines, the app starts normally.

What's wrong with this code? I'm really getting stuck with this.

EDIT I managed to get it working by setting up the aspect in the classes that needed to be customized, like:

[[UISearchBar appearance]setBackgroundImage:[UIImage imageNamed:@"searchBarBackground"]];

But now, when I tap on the SearchBar, it gives me the default aspect.


Solution

  • I managed to make it work this way:

    #define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
    #define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
    #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
    #define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
    #define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
    
    
    UIImage *toolbarImage = [UIImage imageNamed:@"toolbarBackground"];
    [self.navigationController.toolbar setBackgroundImage:toolbarImage forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    
    UIImage *searchBarImage = [UIImage imageNamed:@"searchBarBackground"];
    if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
         [self.searchDisplayController.searchBar setBackgroundImage:searchBarImage];
     else
         [self.searchDisplayController.searchBar setBackgroundImage:searchBarImage forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    

    In the class where the customization was needed.