Custom InputView for UISearchBar doesn't work

2019-02-15 10:01发布

问题:

I need to set my custom inputView in UISearchBar.

So i wrote following codes , that is working perfectly in iOS5 and iOS6 .

However it doesn't work in iOS7.

for(int i =0; i<[self.searchBar.subviews count]; i++) {
            if([[self.searchBar.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
            {
                [(UITextField*)[searchBar.subviews objectAtIndex:i] setFont:[UIFont fontWithName:@"MyCustomFont" size:15]];
                UITextField* search=(UITextField*)[searchBar.subviews objectAtIndex:i];
                search.delegate = self;

                [(UITextField*)[self.searchBar.subviews objectAtIndex:i] setInputView:self.customKeyboard];
                [self.customKeyboard setTextView:search];
            }
        }



        [self.sBar reloadInputViews];

How can i do that?

回答1:

The searchBar sub views hierarchy has been changed in iOS7, try the below:

iOS7:

NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];

iOS6 and before:

NSArray *searchBarSubViews =  self.searchBar.subviews;

Try below updated function:

NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];
for(int i =0; i<[searchBarSubViews count]; i++) {
    if([[searchBarSubViews objectAtIndex:i] isKindOfClass:[UITextField class]])
    {
        UITextField* search=(UITextField*)[searchBarSubViews objectAtIndex:i];
        [search setFont:[UIFont fontWithName:@"MyCustomFont" size:15]];
        search.delegate = self;

        [search setInputView:self.customKeyboard];
        [self.customKeyboard setTextView:search];
    }
}
[self.sBar reloadInputViews];