How to change the default text of Cancel Button which appears in the UISearchBar +iPhone

后端 未结 15 2013
慢半拍i
慢半拍i 2020-12-01 03:04

I am developing an Application where I wanted to change the text of Search String in the SearchBar. I wanted to change the text of Cancel Button Also which appears next to t

15条回答
  •  情话喂你
    2020-12-01 03:25

    I would like to fix the UIAppearance technique, as yar1vn code won't work with Xcode 5. With the following you will have code that works perfectly for both iOS 6 and iOS 7.

    First, you need to understand that the cancel button is a private UINavigationButton:UIButton. Hence, it is not an UIBarButtonItem. After some inspection, it appears that UINavigationButton will respond to those UIAppearance selectors:

    // inherited from UINavigationButton
    @selector(setTintColor:)
    @selector(setBackgroundImage:forState:style:barMetrics:)
    @selector(setBackgroundImage:forState:barMetrics:)
    @selector(setTitleTextAttributes:forState:)
    @selector(setBackgroundVerticalPositionAdjustment:forBarMetrics:)
    @selector(setTitlePositionAdjustment:forBarMetrics:)
    @selector(setBackButtonBackgroundImage:forState:barMetrics:)
    @selector(setBackButtonTitlePositionAdjustment:forBarMetrics:)
    @selector(setBackButtonBackgroundVerticalPositionAdjustment:forBarMetrics:)
    
    // inherited from UIButton
    @selector(setTitle:forState:)
    

    Coincidentally, those selectors match those of a UIBarButtonItem. Meaning the trick is to use two separate UIAppearance to handle the private class UINavigationButton.

    /* dual appearance technique by Cœur to customize a UINavigationButton */
    Class barClass = [UISearchBar self];
    
    UIBarButtonItem *barButtonItemAppearanceInBar = [UIBarButtonItem appearanceWhenContainedIn:barClass, nil];
    [barButtonItemAppearanceInBar setTintColor:...];
    [barButtonItemAppearanceInBar setBackgroundImage:... forState:... style:... barMetrics:...];
    [barButtonItemAppearanceInBar setBackgroundImage:... forState:... barMetrics:...];
    [barButtonItemAppearanceInBar setTitleTextAttributes:... forState:...];
    [barButtonItemAppearanceInBar setBackgroundVerticalPositionAdjustment:... forBarMetrics:...];
    [barButtonItemAppearanceInBar setTitlePositionAdjustment:... forBarMetrics:...];
    [barButtonItemAppearanceInBar setBackButtonBackgroundImage:... forState:... barMetrics:...];
    [barButtonItemAppearanceInBar setBackButtonTitlePositionAdjustment:... forBarMetrics:...];
    [barButtonItemAppearanceInBar setBackButtonBackgroundVerticalPositionAdjustment:... forBarMetrics:...];
    
    UIButton *buttonAppearanceInBar = [UIButton appearanceWhenContainedIn:barClass, nil];
    [buttonAppearanceInBar setTitle:... forState:...];
    

    Now, this technique works for the Cancel button, but it also works for the Back button if you change the barClass to [UINavigationBar self].

提交回复
热议问题