原由是首先今天开始了一个新的项目,而后首页有个UITabBar并且背景是透明的,原本心想这也没啥,以前也作过很多相似的,直接复制粘贴不就OK了嘛!,而后粘过来后才发现代码都失效了(均为iOS8以前的修改方法),而后又各类百度、各类谷歌试了半天也没啥卵用,最后在一个角落发现一个方法修改为功,遂记录下来。字体
此方法与以前的方法不一样,以前的都是经过遍历将子View remove掉或者经过KVO来修改,因此当iOS系统版本发生变化的时候,可能就会受到影响(好像如今就受到了影响/(ㄒoㄒ)/~~)。本方法是直接设置搜索栏的背景图片,使用的是系统的API,风险明显就下降了吧。spa
一、先进行图片的生成(代码生成),也能够经过UI设计师预先切好的图片。设计
/** * 生成图片 * * @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; }
二、而后就能够设置了code
UIImage* searchBarBg = [self GetImageWithColor:[UIColor clearColor] andHeight:32.0f]; //设置背景图片 [_searchBar setBackgroundImage:searchBarBg]; //设置背景色 [_searchBar setBackgroundColor:[UIColor clearColor]]; //设置文本框背景 [_searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
OK,这样就大功告成了!orm
一、设置字体颜色、默认字体颜色等图片
UITextField *searchField = [_searchBar valueForKey:@"_searchField"]; searchField.textColor = [UIColor whiteColor]; [searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
二、修改放大镜rem
UIImage *image = [UIImage imageNamed:@"cl_tab2_gray"]; UIImageView *iconView = [[UIImageView alloc] initWithImage:image]; iconView.frame = CGRectMake(0, 0, image.size.width , image.size.height); searchField.leftView = iconView;