需求: 在iOS 10中, 使用系統(tǒng)
UISearchBar, 使搜索圖標(biāo)和placeholder在無文本時(shí)靠左顯示.
系統(tǒng)UISearchBar效果圖:

需求效果圖:

思路:
兩種方案:
- 找到
UISearchBar上的放大鏡圖標(biāo), 修改Frame. 同時(shí)判斷在有無文本內(nèi)容更改placeholder的顏色. - 利用
UISearchBar的Text有值后, 放大鏡自動(dòng)靠左特性, 讓UISearchBar設(shè)置一個(gè)默認(rèn)的Text, 在點(diǎn)擊UISearchBar開始編輯后, 如果沒有值,設(shè)置Text為則@"", 同時(shí)還要根據(jù)狀態(tài)修改placeholderLabel的顏色.(太繁瑣, 不推薦!)
實(shí)現(xiàn)代碼:
@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];
}
}
// 設(shè)置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]) {
// 無文本時(shí), 顯示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 -根據(jù)文本內(nèi)容設(shè)置searchBar顏色及clearButtonMode
- (void)updateSeachBar
{
if ([_searchBar.text isEqualToString:@""]) {// 文本內(nèi)容為空時(shí)
UITextField *searchField = [_searchBar valueForKey:@"_searchField"];
// 修改textColor為placeholderColor
searchField.textColor = [searchField valueForKeyPath:@"_placeholderLabel.textColor"];
searchField.text = searchField.placeholder;
// 去除右側(cè)clearButton
searchField.clearButtonMode = UITextFieldViewModeNever;
}
}
- (void)dealloc
{
// 移除觀察者
[_searchBar removeObserver:self forKeyPath:@"frame"];
}