如何自定义iOS7中的UISearchBar颜色?

问题描述:

我已经搜索了很多,但找不到一个很好的答案。如何自定义iOS7中的UISearchBar颜色?

我想更改内部圆角视图的backgroundColor。

就像在Tweetbot上的搜索点击它从灰色变为蓝色。

据我所知,我可能需要迭代子视图,但我不知道如何得到正确的对象。 (为的backgroundColor它不是_searchLabel)

该元素的默认对比度是如此糟糕,这甚至不是滑稽:(

+2

http://*.com/questions/13817330 /如何更改内部背景颜色的uisearchbar组件上的ios?rq = 1 这是否有帮助? – 4GetFullOf

+0

nope :(我不想添加一个背景图片,只是改变内部圆形视图的颜色 – 1b0t

+0

我的意思是解决方案2下面的答案你的提及 – 4GetFullOf

使用此代码。

_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.contentView.bounds.size.width, 44.0f)]; 
_searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth; 
_searchBar.delegate   = self; 
[self.view addSubView:_searchBar]; 

UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"]; 
txfSearchField.backgroundColor = [UIColor redColor]; 
+0

这会导致应用商店拒绝。 – STANGMMX

好吧,这个工程。但是要注意。你不能设置一个UIBarStyle事先或将压倒一切 https://*.com/a/19836215/1252720

如果你还在寻找一个更好的答案,我只是碰到这个线程迷迷糊糊地发现了一个很好的解决方案:UISearchBar text color change in iOS 7

如果你看一下通过桑迪普 - Systematix给出的答案(不接受的答案,但答案正下方),他提到了一个非常干净的方式修改子视图中的任何类用这种方法:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]]; 

您可以在Apple的文档中阅读更多关于这一点:https://developer.apple.com/library/ios/documentation/uikit/reference/UIAppearance_Protocol/Reference/Reference.html

这就是说,这里就是你需要改变的UITextField的的UISearchBar内的白色,圆形的背景是什么:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor redColor]]; 

现在,如果你需要创建不同的风格不同的UISearchBars,您只需创建的UISearchBar的一个子类,你最终的东西是这样的:

[[UITextField appearanceWhenContainedIn:[MyCustomSearchBar class], nil] setBackgroundColor:[UIColor redColor]];