您好,登錄后才能下訂單哦!
怎么在iOS中使用UISearchBar創建一個搜索框?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
搜索頁面
1.實現代理UISearchBarDelegate
@interface SearchViewController ()<UISearchBarDelegate>
2.創建一個UISearchBar為屬性
@property (nonatomic, strong) UISearchBar *searchBar;
3.進入頁面后彈起鍵盤和離開頁面前收起鍵盤
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if (!_searchBar.isFirstResponder) { [self.searchBar becomeFirstResponder]; } } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.searchBar resignFirstResponder]; }
4.具體實現
- (void)setBarButtonItem { //隱藏導航欄上的返回按鈕 [self.navigationItem setHidesBackButton:YES]; //用來放searchBar的View UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(5, 7, self.view.frame.size.width, 30)]; //創建searchBar UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(titleView.frame) - 15, 30)]; //默認提示文字 searchBar.placeholder = @"搜索內容"; //背景圖片 searchBar.backgroundImage = [UIImage imageNamed:@"clearImage"]; //代理 searchBar.delegate = self; //顯示右側取消按鈕 searchBar.showsCancelButton = YES; //光標顏色 searchBar.tintColor = UIColorFromRGB(0x595959); //拿到searchBar的輸入框 UITextField *searchTextField = [searchBar valueForKey:@"_searchField"]; //字體大小 searchTextField.font = [UIFont systemFontOfSize:15]; //輸入框背景顏色 searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1]; //拿到取消按鈕 UIButton *cancleBtn = [searchBar valueForKey:@"cancelButton"]; //設置按鈕上的文字 [cancleBtn setTitle:@"取消" forState:UIControlStateNormal]; //設置按鈕上文字的顏色 [cancleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [titleView addSubview:searchBar]; self.searchBar = searchBar; self.navigationItem.titleView = titleView; }
5.實現代理方法
#pragma mark - UISearchBarDelegate - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{ return YES; } - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { searchBar.showsCancelButton = YES; } - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { NSLog(@"SearchButton"); } - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { [self.searchBar resignFirstResponder]; [self.navigationController popViewControllerAnimated:YES]; } - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { searchBar.showsCancelButton = YES; } - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { NSString *inputStr = searchText; [self.results removeAllObjects]; for (ElderModel *model in self.dataArray) { if ([model.name.lowercaseString rangeOfString:inputStr.lowercaseString].location != NSNotFound) { [self.results addObject:model]; } } [self.tableView reloadData]; }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。