搜索栏在导航栏中时更改颜色

5
我在导航项的标题视图中添加了一个搜索栏。搜索功能正常工作,但使用导航控制器时,搜索栏的背景颜色会改变,如下所示。
我唯一更改颜色的地方是通过Xcode在Storyboard中更改导航项的颜色。
以下是将搜索栏放置在标题视图中的相关代码。
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
[_searchController.searchBar sizeToFit];
self.navigationItem.titleView = _searchController.searchBar;

什么原因导致这种颜色?
尝试使用bartint更改颜色。
[_searchController.searchBar setBarTintColor:[UIColor clearColor]];

但我遇到了这个问题 图片描述

而且还有一些不正常工作的事情。

[_searchController.searchBar setBarTintColor:self.navigationController.navigationBar.tintColor];
_searchController.searchBar.backgroundColor = self.navigationController.navigationBar.tintColor;

同时使用 backgroundColor 属性时,似乎这个颜色与设置的不一样。看这里使用 redColor:

enter image description here


我尝试了clearColor,但没有起作用。 - Nick Ginanto
如何制作像您上传的问题图像一样的gif图像? - Dharmesh Dhorajiya
我在 OS X 上使用 LICEcap。 - Nick Ginanto
2个回答

14

需要设置UISearchBartint color

UISearchBar *search=[[UISearchBar alloc]initWithFrame:CGRectMake(10, 20, 100, 20)];
[search setBarTintColor:[UIColor clearColor]];
search.backgroundImage=[UIImage new];
self.navigationItem.titleView=search;

现在导航栏看起来像下面的图片:

enter image description here


不幸的是,它不起作用。我添加了GIF以展示编辑中代码的行为。 - Nick Ginanto
5
这个代码 search.backgroundImage=[UIImage new]; 修复了我的问题;不需要设置barTintColor属性。 - Dylan Hand

4
对于Swift用户,只需添加以下两行代码:
searchBar.barTintColor = UIColor.clearColor()
searchBar.backgroundImage = UIImage()
self.navigationItem.titleView = searchBar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接