UISearchBar 修改背景顏色透明
阿新 • • 發佈:2019-02-01
輸入相關關鍵字在百度中能搜尋出來很多,但是都不靠譜,於是Google了一下,在StackOverFlow中找到一個蠻靠譜的方法,試了可行。
with iOS8 sdks apple moved @"UISearchBarBackground" view one level deeper, so have will need to look at subviews of the child-views as bellow,.
for (UIView *subview in searchBar.subviews) { for(UIView* grandSonView insubview.subviews){ if ([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) { grandSonView.alpha = 0.0f; }else if([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarTextField")] ){ NSLog(@"Keep textfiedld bkg color"); }else{ grandSonView.alpha = 0.0f; } }//for cacheViews }//subviews
耶!
接下來,我又發現一位博主分享的文章,寫的很詳細,而且解決方案看起來會更加優雅,不像上面給的那樣暴力粗魯。^_^
文章在這裡。
這裡貼出程式碼:
- (void)viewDidLoad { [super viewDidLoad]; // 1 UIImage* 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(); return image; }
修改APP內全域性UISearchBar樣式:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIColor* myColor = [UIColor colorWithRed:0 green:0.48 blue:1 alpha:1]; // set your desired background color here UIImage* 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]; return YES; }
給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];
http://www.cnblogs.com/emmet7life/p/4648383.html