zoukankan      html  css  js  c++  java
  • UISearchBar clearButton

    When the searchBar:textDidChange: method of the UISearchBarDelegate gets called because of the user tapping the 'clear' button, the searchBar hasn't become the first responder yet, so we can take advantage of that in order to detect when the user in fact intended to clear the search and not bring focus to the searchBar and/or do something else.

    To keep track of that, we need to declare a BOOL ivar in our viewController that is also the searchBar delegate (let's call it shouldBeginEditing) and set it with an initial value of YES (supposing our viewController class is called SearchViewController):

    @interface SearchViewController : UIViewController <UISearchBarDelegate> {
        // 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;
        }
    }
    ...
    @end

    Later on, in the UISearchBarDelegate, we implement the searchBar:textDidChange: andsearchBarShouldBeginEditing: methods:

    - (void)searchBar:(UISearchBar *)bar textDidChange:(NSString *)searchText {
        NSLog(@"searchBar:textDidChange: isFirstResponder: %i", [self.searchBar isFirstResponder]);
        if(![searchBar isFirstResponder]) {
            // user tapped the 'clear' button
            shouldBeginEditing = NO;
            // do whatever I want to happen when the user clears the search...
        }
    }
    
    
    - (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;
    }
    

    http://stackoverflow.com/questions/1092246/uisearchbar-clearbutton-forces-the-keyboard-to-appear/3852509#3852509

  • 相关阅读:
    文件高级应用和函数基础
    字符编码,文件操作
    数据类型分类,深浅拷贝
    容器数据类型内置方法
    数字类型和字符串类型内置方法
    流程控制循环
    python 运算和流程控制
    【MySQL】SQL教程
    【MySQL】数据库字段类型
    【java】HashSet
  • 原文地址:https://www.cnblogs.com/Clin/p/3383779.html
Copyright © 2011-2022 走看看