UISearchBar使用

/*取消按鈕點擊事件*/
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{  
   [self doSearch:searchBar];  

}  

/*鍵盤搜索按鈕點擊事件*/  
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{  
  [searchBar resignFirstResponder];   
  [self doSearch:searchBar];  

}  

/*搜索方法*/  

- (void)doSearch:(UISearchBar *)searchBar{    ...  }  

//UISearchBar上按鈕的默認文字爲Cancel,如果想改爲其他文字請調用以下代碼
for(id cc in [searchtext subviews]){  
  if([cc isKindOfClass:[UIButton class]]){  
     UIButton *btn = (UIButton *)cc;  
     [btn setTitle:@"取消"  forState:UIControlStateNormal];
  }

}

/*修改搜索框背景*/

seachBar.backgroundColor=[UIColor clearColor];


/*去掉搜索框背景*/
//1.
[[searchbar.subviews objectAtIndex:0]removeFromSuperview];
//2.
for (UIView *subview in seachBar.subviews)
{
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
{
[subview removeFromSuperview];
break;
}

}

/*自定義背景*/
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"40-di.png"]];
[mySearchBar insertSubview:imageView atIndex:1];
[imageView release];

/*輸入搜索文字時隱藏搜索按鈕,清空時顯示*/
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = YES;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:YES animated:YES];
return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = NO;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:NO animated:YES];
return YES;
}

/*改變搜索按鈕文字*/
//改變UISearchBar取消按鈕字體
for(id cc in [searchBar subviews])
{
if([cc isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)cc;
[btn setTitle:@"搜索" forState:UIControlStateNormal];
}
}

下圖有點小,可以下載至本地放大查看。

當你在seachBar中輸入字母之前的時候,只是用鼠標選中searchBar的時候,如圖

終端輸出截圖如下:(這個時候調用先shouldBeginEditing,之後調用didBeginEditing,)
當你希望選中UISearchBar的時候,鍵盤自動調用加載到界面,你需要將下面函數的返回值設置爲YES;
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {   
   NSLog(@"shouldBeginEditing");
   returnYES;
}

當你在seachBar中輸入字母Dditring的時候,如圖:

終端顯示

當你點擊鍵盤右下角的Done的時候,調用searchButtonClicked

當在Viewdidload裏面加入下面兩行的時候,

界面searchBar顯示

當在Viewdidload裏面加入下面一行的時候

界面searchBar顯示:

UISearchBar的相關屬性:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章