UISearchbar clearButton forces the keyboard to appear

后端 未结 12 1929
暖寄归人
暖寄归人 2020-11-30 20:40

I have a UISearchBar which acts as a live filter for a table view. When the keyboard is dismissed via endEditing:, the query text and the gray circular \"clear\" button rem

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 21:22

    I found a pretty safe way to know if the clear button has been pressed, and ignore the times when the user just delete the last character of the UISearchBar. Here it is :

    - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
        _isRemovingTextWithBackspace = ([searchBar.text stringByReplacingCharactersInRange:range withString:text].length == 0);
    
        return YES;
    }
    
    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
    {
        if (searchText.length == 0 && !_isRemovingTextWithBackspace)
        {
            NSLog(@"Has clicked on clear !");
        }
    }
    

    Pretty simple and straightforward, isn't it :) ? The only thing to note is that if the user clicks the clear button when editing the UISearchBar's UITextField, you will have two pings, whereas you'll get only one if the user clicks it when it is not being edited.


    Edit : I can't test it, but here's the swift version, as per Rotem :

    var isRemovingTextWithBackspace = false
    
    func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
    {
        self.isRemovingTextWithBackspace = (NSString(string: searchBar.text!).stringByReplacingCharactersInRange(range, withString: text).characters.count == 0)
        return true
    }
    
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String)
    {
        if searchText.characters.count == 0 && !isRemovingTextWithBackspace
        { 
            NSLog("Has clicked on clear !")
        }
    }
    

    @Rotem's update (Swift2):

    var isRemovingTextWithBackspace = false
    
    func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        self.isRemovingTextWithBackspace = (NSString(string: searchBar.text!).stringByReplacingCharactersInRange(range, withString: text).characters.count == 0)
        return true
    }
    
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.characters.count == 0 && !isRemovingTextWithBackspace {
            NSLog("Has clicked on clear!")
        }
    }
    

提交回复
热议问题