Dismissing keyboard from UISearchBar when the X button is tapped

前端 未结 14 1217
眼角桃花
眼角桃花 2020-12-24 07:42

I\'m using the UISearchBar (but not the SearchDisplayController that\'s typically used in conjunction) and I\'d like to dismiss the keyboard when you hit the \'X\' button.

14条回答
  •  一整个雨季
    2020-12-24 08:19

    I used a combination of @radiospiel's answer and also the answer that @Tozar linked to:

    @interface SearchViewController : UIViewController  {
        // all of our ivar declarations go here...
        BOOL shouldBeginEditing;
        ....
    }
    
    ...
    @end
    
    @implementation SearchViewController
    ...
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
        if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
            ...
            shouldBeginEditing = YES;
        }
    }
    ...
    
    - (void) searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
        // TODO - dynamically update the search results here, if we choose to do that.
    
        if (![searchBar isFirstResponder]) {
            // The user clicked the [X] button while the keyboard was hidden
            shouldBeginEditing = NO;
        }
        else if ([searchText length] == 0) {
            // The user clicked the [X] button or otherwise cleared the text.
            [theSearchBar performSelector: @selector(resignFirstResponder)
                            withObject: nil
                            afterDelay: 0.1];
        }
    }
    
    - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)bar {
        // reset the shouldBeginEditing BOOL ivar to YES, but first take its value and use it to return it from the method call
        BOOL boolToReturn = shouldBeginEditing;
        shouldBeginEditing = YES;
        return boolToReturn;
    }
    @end
    

提交回复
热议问题