Designing iOS SearchBar

前端 未结 1 1120
日久生厌
日久生厌 2021-02-04 12:25

I want to have a simple SearchBar in ObjectiveC. Using UISearchBar or UISearchBarDelegate is confusing me. I could have used a UITextField

1条回答
  •  情话喂你
    2021-02-04 12:43

    Just make your view controller implement the UISearchBarDelegate. In your xib file, all you need to do is to add a UISearchBar to your view and configure it as necessary, create an outlet for it (optional really but helps to be explicit), and assign the delegate outlet to your view controller.

    Then, to respond to the search bar events, implement the UISearchBarDelegate protocol methods as necessary. For example:

    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
        [self handleSearch:searchBar];
    }
    
    - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
        [self handleSearch:searchBar];
    }
    
    - (void)handleSearch:(UISearchBar *)searchBar {
        NSLog(@"User searched for %@", searchBar.text);
        [searchBar resignFirstResponder]; // if you want the keyboard to go away
    }
    
    - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
        NSLog(@"User canceled search");
        [searchBar resignFirstResponder]; // if you want the keyboard to go away
    }
    

    0 讨论(0)
提交回复
热议问题