UISearchBar 修改背景颜色透明

输入相关关键字在百度中能搜索出来很多,但是都不靠谱,于是Google了一下,在StackOverFlow中找到一个蛮靠谱的方法,试了可行。

1.for(UIView *subviewinsearchBar.subviews) {for(UIView* grandSonViewinsubview.subviews){if([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {

grandSonView.alpha=0.0f;

}elseif([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarTextField")] ){

NSLog(@"Keep textfiedld bkg color");

}else{

grandSonView.alpha=0.0f;

}

}//for cacheViews}//subviews

接下来,我又发现一位博主分享的文章,写的很详细,而且解决方案看起来会更加优雅,不像上面给的那样暴力粗鲁。^_^

文章在这里

这里贴出代码:

- (void)viewDidLoad

{

[super viewDidLoad];//1UIImage* clearImg = [CDViewController imageWithColor:[UIColor clearColor] andHeight:32.0f];//2[_searchBar setBackgroundImage:clearImg];//3[_searchBar setSearchFieldBackgroundImage:clearImg forState:UIControlStateNormal];//4[_searchBar setBackgroundColor:[UIColor clearColor]];

}+ (UIImage*) imageWithColor:(UIColor*)color andHeight:(CGFloat)height

{

CGRect rect= CGRectMake(0.0f,0.0f,1.0f, height);

UIGraphicsBeginImageContext(rect.size);

CGContextRef context=UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [color CGColor]);

CGContextFillRect(context, rect);

UIImage*image =UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();returnimage;

}

修改APP内全局UISearchBar样式:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

UIColor* myColor = [UIColor colorWithRed:0green:0.48blue:1alpha:1];//set your desired background color hereUIImage* clearImg = [CDViewController imageWithColor:[UIColor clearColor] andHeight:1.0f];

UIImage* coloredImg = [CDViewController imageWithColor:myColor andHeight:32.0f];

[[UISearchBar appearance] setBackgroundColor:[UIColor clearColor]];

[[UISearchBar appearance] setBackgroundImage:clearImg];

[[UISearchBar appearance] setSearchFieldBackgroundImage:coloredImg forState:UIControlStateNormal];returnYES;

}

给ScopeBar设置透明背景:

UIImage* clearImg = [CDViewController imageWithColor:[UIColor clearColor] andHeight:1.0f];

[_searchBar setScopeButtonTitles:nil];

[_searchBar setScopeBarBackgroundImage:clearImg];

[_searchBar setScopeBarButtonBackgroundImage:clearImg forState:UIControlStateNormal];

[_searchBar setScopeBarButtonDividerImage:clearImg forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容