前段时间做了一个UISearchBar相关的需求,今天也总结以下。
1、UISearchBar自定义背景、取消按钮中文设置
- UISearchBar *seachBar=[[UISearchBar alloc] init];
-
- seachBar.backgroundColor=[UIColor clearColor];
-
- [[searchbar.subviews objectAtIndex:0]removeFromSuperview];
-
- for (UIView *subview in seachBar.subviews)
- {
- if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
- {
- [subview removeFromSuperview];
- break;
- }
- }
-
- UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"40-di.png"]];
- [searchBar insertSubview:imageView atIndex:1];
-
- - (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;
- }
-
- for (id aa in [searchBar subviews]) {
- if ([aa isKindOfClass:[UIButton class]]) {
- UIButton *btn = (UIButton *)aa;
- [btn setTitle:@"取消" forState:UIControlStateNormal];
- }
- }
2、UISearchBar 的delegate方法
- #pragma mark 搜索控件
- - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
- UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
- FirstViewController *fVC = [mainStory instantiateViewControllerWithIdentifier:@"goFirstView"];
- fVC.showStr = self.searchBar.text;
- [self presentModalViewController:fVC animated:YES];
- }
-
- - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
-
- }
-
- - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
- self.soundBtn.hidden = YES;
- [self searchBar:searchBar activate:YES];
-
- }
-
- - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
- self.searchBar.text = @"";
- self.soundBtn.hidden = NO;
- [self searchBar:searchBar activate:NO];
- }
-
- - (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active{
- if (!active) {
- [self.searchBar resignFirstResponder];
- }
-
- [self.searchBar setShowsCancelButton:active animated:YES];
-
- for (id aa in [searchBar subviews]) {
- if ([aa isKindOfClass:[UIButton class]]) {
- UIButton *btn = (UIButton *)aa;
- [btn setTitle:@"取消" forState:UIControlStateNormal];
- }
- }
- }
UISearchBar相关,布布扣,bubuko.com
UISearchBar相关
原文:http://www.cnblogs.com/ranger-jlu/p/3885609.html