UISearchBar设置barTintColor“无效”
2017-01-06 本文已影响226人
奶茶007
设置UISearchBar背景色,就调用barTintColor,发现无效,可是查了官方文档和别人的blog,都说这个属性就可以。后来又读到以下一段文字:
UISearchBar是由两个subView组成的,一个是UISearchBarBackGround,另一个是UITextField.
就用于Reveal工具调试,才找到原因,原来是UITextField把UISearchBarBackGround盖住了。示例代码如下:
ViewController.m
//自定义导航栏
CGFloat navViewH = 44;
UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
// navView.backgroundColor = [UIColor blueColor];
//自定义导航栏左侧按钮
CGFloat leftImageViewX = 10;
CGFloat leftImageViewW = 15;
CGFloat leftImageViewH = 25;
CGFloat leftImageViewY = (navViewH - leftImageViewH)/2;
UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(leftImageViewX, leftImageViewY, leftImageViewW, leftImageViewH)];
leftImageView.image = [UIImage imageNamed:@"8-2"];
[navView addSubview:leftImageView];
//自定义中间搜索框
CGFloat searchBarW = kScreenWidth * 3/4;
CGFloat searchBorder = 20;
CGFloat searchBarH = 30;
CGFloat searchBarY = (navViewH - searchBarH)/2;
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftImageView.frame) + searchBorder, searchBarY, searchBarW, searchBarH)];
[navView addSubview:searchBar];
searchBar.layer.cornerRadius = 15;
searchBar.clipsToBounds = YES;
searchBar.placeholder = @"请输入目的地、地标或民宿名称";
searchBar.barTintColor = [UIColor yellowColor];
//去掉上下边框黑色
// searchBar.backgroundImage = [[UIImage alloc] init];
self.navigationController.navigationBar.items.lastObject.titleView = navView;
从图上可以看出,是SearchFeild遮住了SearchBackgroud
498970DF-5465-4535-A41A-B69F4017128A.png
知道了原因就好办了,用searchBar自带方法,解决方案如下:
[searchBar setSearchFieldBackgroundImage:[UIImage createImageWithColor:[UIColor greenColor]] forState:UIControlStateNormal];
Reveal的截图如下:
8E4FCB3B-CB37-4974-84D1-E9ED0FEA327C.png