廢話不多說,直接上代碼
//寫一個背景View了嚎,貼在導航控制器上
UIView *BJview = [[UIView alloc] initWithFrame:CGRectMake(40, 33,
self.view.frame.size.width - 80, 40)];
self.navigationItem.titleView = BJview;
//創(chuàng)建seachBar
self.seachBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, BJview.bounds.size.width, 40)];
//去掉seachBar的黑線
self.seachBar.backgroundImage = [UIImage new];
self.seachBar.delegate = self;
self.seachBar.placeholder = @"請輸入要搜索的內(nèi)容";
//成為鍵盤的第一響應者
[self.seachBar becomeFirstResponder];
[BJview addSubview:self.seachBar];
//通過KVC拿到textField
UITextField *seachTextFild = [self.seachBar valueForKey:@"searchField"];
拿到textField之后就可以肆意妄為了
//修改字體顏色
seachTextFild.textColor = [UIColor redColor];
//修改字體大小
seachTextFild.font = [UIFont systemFontOfSize:14];
//修改光標顏色
[seachTextFild setTintColor:[UIColor colorWithRed:35/255.0 green:185/255.0 blue:165/255.0 alpha:1.0]];
//更改searchBar 中PlaceHolder 字體顏色
[searchField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
self.seachTextFild = seachTextFild;
//修改搜索圖標
UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sear"]];
img.frame = CGRectMake(10, 0,20,20);
self.searchField.leftView = img;
self.searchField.leftViewMode = UITextFieldViewModeAlways;
//修改clearButton
UIButton *clearButton = [self.searchField valueForKey:@"_clearButton"];
[clearButton setImage:[UIImage imageNamed:@"dele.png"] forState:UIControlStateNormal];
D68CB859-5F35-4CDF-A8F5-2601132829F0.png
UISearchBar 的代理方法
//代理方法 實時監(jiān)聽輸入框的文字變動
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSLog(@"%@",searchText);
}
//searchBar的確定點擊事件
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
NSLog(@"%@",self.seachBar.text);
}
將要開始編輯時的回調(diào)萎津,返回為NO,則不能編輯
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;
已經(jīng)開始編輯時的回調(diào)
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar;
將要結(jié)束編輯時的回調(diào)
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
已經(jīng)結(jié)束編輯的回調(diào)
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar;
編輯文字改變前的回調(diào)递宅,返回NO則不能加入新的編輯文字
-(BOOL)searchBar: (UISearchBar )searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString )text;
書本按鈕點擊的回調(diào)
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar;
取消按鈕點擊的回調(diào)
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar;
搜索結(jié)果按鈕點擊的回調(diào)
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar;
搜索欄的附加試圖中切換按鈕觸發(fā)的回調(diào)
-(void)searchBar:(UISearchBar*)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope;
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者