修改IOS中UISearchBar的取消按钮背景、搜索内容输入文本框背景和UISearchBar的背景

来源:互联网 发布:地图数据采集是什么 编辑:程序博客网 时间:2024/05/22 13:49

1、添加UISearchBar到父View

_searchBar = [[UISearchBar alloc]init];_searchBar.frame = CGRectMake(0, 0, self.view.frame.size.width, kSeachBarH);_searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;_searchBar.delegate = self;_searchBar.placeholder = @"请输入姓名、公司名称、公司产品名称";[self.view addSubview:_searchBar];
2、修改搜索框背景
UIImage *img = [UIImage resizedImage:@"find_bg.png"];[_searchBar setBackgroundImage:img];

3、修改搜索输入框内左侧的指示图标

[_searchBar setImage:[UIImage resizedImage:@"ic_search.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

4、修改搜索输入文本的背景

[_searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"login_btn_input_side.png"] forState:UIControlStateNormal];

注:对于设计人员提供的搜索输入文本的背景,若提供的是一个圆角的小方块,按常理我们会使用拉伸图片的中间部分的方法, 经测试显示效果如下:

若让设计人员重新提供一张固定高度的图片(比如高是60),当做搜索输入文本的背景,效果图如下:

5、修改UISearchBar右侧的取消按钮文字颜色及背景图片

#pragma mark 搜索框的代理方法,搜索输入框获得焦点(聚焦)-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{[searchBar setShowsCancelButton:YES animated:YES];// 修改UISearchBar右侧的取消按钮文字颜色及背景图片for (UIView *searchbuttons in [searchBar subviews]){if ([searchbuttons isKindOfClass:[UIButton class]]) {UIButton *cancelButton = (UIButton*)searchbuttons;// 修改文字颜色[cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];[cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];// 修改按钮背景[cancelButton setBackgroundImage:[UIImage resizedImage:@"login_btn_login.png"] forState:UIControlStateNormal];[cancelButton setBackgroundImage:nil forState:UIControlStateHighlighted];}}}
注:修改取消按钮文字颜色及背景图片的代码片段,一定要放到取消按钮会显示代理方法中修改,否则遍历找不着呀,那就修改不了了。
0 0
原创粉丝点击