1. 程式人生 > >iOS之讓UISearchBar搜索圖標和placeholder靠左顯示

iOS之讓UISearchBar搜索圖標和placeholder靠左顯示

nsstring mode ace change 更改 ring val 搜索 class

系統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"]; }



iOS之讓UISearchBar搜索圖標和placeholder靠左顯示