记录一篇曾经对开发帮助的文章,UISearchBar定制。
转自:http://blog.csdn.net/djl461260911/article/details/41855905?utm_source=tuicool
谢谢大神分享。
因为需求是定制如图所示的searchBar
我的实现方式如下:
for (UIView *view in self.searchBar.subviews) {
if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
[[view.subviews objectAtIndex:0] removeFromSuperview];
[[view.subviews objectAtIndex:0] setBackgroundColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.3]];
[[view.subviews objectAtIndex:0] setFrame:CGRectMake(8, 8, 312, 27.5)];
break;
}
}
主要受教育的文段摘录:
这里,介绍一个刚刚学到的技巧:我们可以使用UIView的私有方法recursiveDescription来看一下UI控件的视图层次结构,在控制台打印出它的继承关系。
如:po [self.searchBar recursiveDescription]
打印结果如下:
从以上可以看出,在iOS7.0之前,UISearchbar视图里直接包含UISearchBarBackground和UISearchBarTextField两个视图,而在iOS7.0及之后,UISearchbar视图里包含的是一个UIView视图,然后UIView视图里面才是UISearchBarBackground和UISearchBarTextField两个视图。相当于做了一次View的封装。
所以去除UISearchbar视图里的UISearchBarBackground之后,UISearchbar的背景也就透明了,同时也可以自定义颜色等。
使用如下代码即实现目的:
- for (UIView *view in self.searchBar.subviews) {
- // for before iOS7.0
- if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
- [view removeFromSuperview];
- break;
- }
- // for later iOS7.0(include)
- if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
- [[view.subviews objectAtIndex:0] removeFromSuperview];
- break;
- }
- }
而对于以上项目截图的实现效果,并没有使用以上这段实现。而是判断系统版本使用如下部分代码:
- if ([self.searchBar respondsToSelector:@selector(barTintColor)]) {
- if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.1) {
- //ios7.1
- [[[[self.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
- [self.searchBar setBackgroundColor:[UIColor clearColor]];
- }else{
- //ios7.0
- [self.searchBar setBarTintColor:[UIColor clearColor]];
- [self.searchBar setBackgroundColor:[UIColor clearColor]];
- }
- }else{
- //iOS7.0 以下
- [[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
- [self.searchBar setBackgroundColor:[UIColor clearColor]];
- }