UISearBar实用技巧

作者: FlyElephant | 来源:发表于2016-06-02 17:12 被阅读505次

UISearBar作为搜索条有的时候我们需要做一些自定的内容,让它看着有点与众不同,先来看一张效果图:

SearBar.gif

第一个搜索框自定义设置的比较多,颜色设置的有点夸张,仅供参考,设置过程如下:
1.设置默认的搜索文字

self.searchBar.placeholder = @"FlyElephant";

2.设置取消按钮的文字及颜色

self.searchBar.cancelTitle = @"中山郎";
self.searchBar.tintColor   = [UIColor greenColor];

3.设置搜索框边框及光标颜色:

UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
if (searchField) {
    [searchField setBackgroundColor:[UIColor whiteColor]];
    searchField.layer.cornerRadius  = 13.0f;
    searchField.layer.borderColor   = [UIColor redColor].CGColor;
    searchField.layer.borderWidth   = 1;
    searchField.layer.masksToBounds = YES;
    //光标颜色
    [searchField setTintColor:[UIColor blueColor]];
}

4.取消默认的灰色背景区域

self.searchBar.backgroundImage = [[UIImage alloc] init];

5.隐藏取消按钮:

self.nextSearchBar.showsCancelButton=NO;

6.设置输入文本的大小及颜色:

self.searchBar.textColor=[UIColor redColor];
self.searchBar.textFont=[UIFont systemFontOfSize:14];

7.设置迷你搜索框:

self.nextSearchBar.searchBarStyle=UISearchBarStyleMinimal;

第一步和第六步中的属性是通过分类实现:
<pre><code>`

@implementation UISearchBar (FESearchBar)

-(NSString *)cancelTitle{
return [objc_getAssociatedObject(self, cancelTitleKey) string];
}

-(void)setCancelTitle:(NSString *)cancelTitle{
if (IS_IOS9) {
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:cancelTitle];
}else {
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:cancelTitle];
}
objc_setAssociatedObject(self,cancelTitleKey,cancelTitle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIFont *)textFont{
return objc_getAssociatedObject(self, textFontKey);
}

-(void)setTextFont:(UIFont *)textFont{
if (IS_IOS9) {
[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].font = textFont;
}else {
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:textFont];
}
objc_setAssociatedObject(self,textFontKey,textFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIColor *)textColor{
return objc_getAssociatedObject(self, textColorKey);
}

-(void)setTextColor:(UIColor *)textColor{
if (IS_IOS9) {
[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].textColor = textColor;
}else {
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:textColor];
}
objc_setAssociatedObject(self,textColorKey,textColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end`</code></pre>

如果有问题欢迎探讨,代码地址:FlyElephant的GitHub

相关文章

网友评论

    本文标题:UISearBar实用技巧

    本文链接:https://www.haomeiwen.com/subject/erdkdttx.html