Dismissing keyboard from UISearchBar when the X button is tapped

前端 未结 14 1089
眼角桃花
眼角桃花 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:42

    Updated for SWIFT 3:

    Suppose that the user has entered a string in searchfield and clicks x the following code works to hide keyboard when x is pressed

    `

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 
    {
                if searchBar.text == nil || searchBar.text == ""
                {
                    searchBar.perform(#selector(self.resignFirstResponder), with: nil, afterDelay: 0.1)
                }
     }
    

    `

    0 讨论(0)
  • 2020-12-24 08:42

    Another point of view for clear text flow (similar to @TomSwift answer but clearer for me and less tricky). Also, I need to hide Cancel button after exit from the search bar, implement live search (after each symbol) and cover table before user complete search.

    //self.searchHoverView can cover table view
    //performSearchWithSearchBar: method for performing search
    
    #pragma mark - UISearchBarDelegate
    
    - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
        [searchBar setShowsCancelButton:YES animated:YES];
        self.searchHoverView.hidden = NO;
    }
    
    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
        if (searchText.length) {
            [self performSearchWithSearchBar:searchBar];
        } else {
            UIButton *button;
            for (UIView *subView in [searchBar subviews]) {
                for (UIView *view in [subView subviews]) {
                    if ([view isKindOfClass:[UIButton class]]) {
                        button = (UIButton *)view;
                        break;
                    }
                }
            }
    
            if (button) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [button sendActionsForControlEvents:UIControlEventTouchUpInside];
                });
            }
        }
    }
    
    - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
        self.searchBar.text = nil;
    
        [self.searchBar setShowsCancelButton:NO animated:YES];
        [self.searchBar resignFirstResponder];
    
        self.searchHoverView.hidden = YES;
    }
    
    0 讨论(0)
提交回复
热议问题