iOS开发我的天空我的ios进阶

初识UISearchBar

2015-11-10  本文已影响1567人  芝麻绿豆

基本属性

    UIBarStyleDefault 
    UIBarStyleBlack 
    UIBarStyleBlackOpaque 
    UIBarStyleBlackTranslucent 
 [searchBar setBackgroundImage:[UIImage imageNamed:@"infocollectClickImage"]];
[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"infocollectClickImage"] forState:UIControlStateNormal];
searchBar.showsCancelButton = YES;
[searchBar setShowsCancelButton:YES animated:YES];
[searchBar setImage:[UIImage imageNamed:@"search-search-icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

设置cancel/取消按钮

1.利用系统的运行时(Runtime)机制设置:

    UIButton *btn = [[UIButton alloc] init];  
    btn.titleLabel.textAlignment = NSTextAlignmentCenter; 
    [btn setTitle:@"123" forState:UIControlStateNormal];    
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [searchBar setValue:btn forKeyPath:@"cancelButton"];

运行结果:达不到需求,需要调整按钮和搜索框的位置;


2.遍历UISearchBar的子控件,设置里面的button;

   [searchBar setShowsCancelButton:YES animated:YES];
    for ( id searchView in [[[searchBar subviews] lastObject]subviews])
 {       
     YANLog(@"%@",[searchView class]);        
     if ([[searchView class] isSubclassOfClass: NSClassFromString(@"UINavigationButton")]) {                   
                YANLog(@"%@",[searchView class]);
                UIButton *cancelBtn = (UIButton *)searchView;
              //[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                [cancelBtn setTitle:nil forState:UIControlStateNormal];            
                [cancelBtn setBackgroundImage:[UIImage imageNamed:@"AppIcon29x29"] forState:UIControlStateNormal];     
       }
  }

3.利用appearance 设置:

该方法不仅可以设置文字、颜色,还可以设置字体大小;

NSMutableDictionary *attr = [NSMutableDictionary dictionary];    
attr[NSFontAttributeName] = [UIFont systemFontOfSize:13];    
attr[NSForegroundColorAttributeName] = [UIColor redColor];    
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class] , nil] setTitle:@"N"];
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:attr forState:UIControlStateNormal];

运行结果:



注意点:


补充:

方法2与方法3基本可以满足需求;若修改太多,可以Textfile与button自定义一个搜索框;
而且方法2与3可以结合使用:


上一篇 下一篇

猜你喜欢

热点阅读