UISearchBar的默認(rèn)背景色是灰色的,配合一些界面UI時效果不太好,但是沒有直接修改背景色的API調(diào)用.
網(wǎng)上搜索的方法多為iOS8前的修改方法.
例如:
[[searchBar.subviews objectAtIndex:0]removeFromSuperview];
或是
for (UIView *subview in searchBar.subviews)
{
if([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
{
[subview rmoveFromSuperview];
}
}
第一種方法我在iOS8下試過后,直接整個搜索框沒了-_-|||
后來在網(wǎng)上看到一種比較靠譜的方法,直接設(shè)置搜索欄的背景圖片.
下面先進行圖片的生成,當(dāng)然也可以通過用美工預(yù)先切好的圖片.
/**
* 生成圖片
*
* @param color 圖片顏色
* @param height 圖片高度
*
* @return 生成的圖片
*/
+ (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
UIGraphicsBeginImageContext(r.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, r);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
接下來進行設(shè)置
UIImage* searchBarBg = [ViewController GetImageWithColor:[UIColor clearColor] andHeight:32.0f];
//設(shè)置背景圖片
[searchBar setBackgroundImage:searchBarBg];
//設(shè)置背景色
[searchBar setBackgroundColor:[UIColor clearColor]];
//設(shè)置文本框背景
[searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
這樣就可以成功了.