iOS之让UISearchBar搜索图标和placeholder靠左显示
程序员文章站
2022-06-16 17:33:23
系统UISearchBar效果图: 需求效果图: 两种方案: 找到UISearchBar上的放大镜图标, 修改Frame. 同时判断在有无文本内容更改placeholder的颜色. 利用UISearchBar的Text有值后, 放大镜自动靠左特性, 让UISearchBar设置一个默认的Text, ......
系统UISearchBar
效果图:
需求效果图:
两种方案:
- 找到
UISearchBar
上的放大镜图标, 修改Frame. 同时判断在有无文本内容更改placeholder的颜色. - 利用
UISearchBar
的Text有值后, 放大镜自动靠左特性, 让UISearchBar
设置一个默认的Text, 在点击UISearchBar开始编辑后, 如果没有值,设置Text
为则@"", 同时还要根据状态修改placeholderLabel
的颜色.(太繁琐, 不推荐!)
实现代码:
@interface ViewController () <UISearchBarDelegate> /** xib搜索框 */ @property (weak, nonatomic) IBOutlet UISearchBar *searchBar; /** 搜索图片(放大镜) */ @property (nonatomic, weak) UIImageView *imgV; @end @implementation ViewController - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; // 查找放大镜图片ImageView for (UIImageView *imgV in _searchBar.subviews.firstObject.subviews.lastObject.subviews) { if ([imgV isMemberOfClass:[UIImageView class]]) { imgV.frame = CGRectMake(8, 7.5, 13, 13); _imgV = imgV; [_imgV addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil]; } } // 设置searchBar文本颜色 [self updateSeachBar]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { // 修改放大镜Frame前, 移除观察者 [_imgV removeObserver:self forKeyPath:@"frame"]; // 修改Frame _imgV.frame = CGRectMake(8, 7.5, 13, 13); // 再次添加观察者 [_imgV addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil]; } #pragma mark -UISearchBarDelegate代理方法 - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { if ([searchBar.text isEqualToString:searchBar.placeholder]) { // 无文本时, 显示placeholder searchBar.text = @""; } // 获取到UISearchBar中UITextField UITextField *searchField = [searchBar valueForKey:@"_searchField"]; // 开始编辑要修改textColor颜色 searchField.textColor = [UIColor blackColor]; searchField.clearButtonMode = UITextFieldViewModeWhileEditing; } - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { [self updateSeachBar]; } #pragma mark -根据文本内容设置searchBar颜色及clearButtonMode - (void)updateSeachBar { if ([_searchBar.text isEqualToString:@""]) {// 文本内容为空时 UITextField *searchField = [_searchBar valueForKey:@"_searchField"]; // 修改textColor为placeholderColor searchField.textColor = [searchField valueForKeyPath:@"_placeholderLabel.textColor"]; searchField.text = searchField.placeholder; // 去除右侧clearButton searchField.clearButtonMode = UITextFieldViewModeNever; } } - (void)dealloc { // 移除观察者 [_searchBar removeObserver:self forKeyPath:@"frame"]; }