標籤:void ons remove eve 放大 sub field oid hba
系統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靠左顯示