使用KVC自定义UISearchBar的UI

KVC 如果名称错误会崩溃
按钮在输入文本没有获得响应者是isEnabled = false 的, 所以需要处理下
动态改变取消按钮文本有问题 待解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
self.searchBar.resignFirstResponder()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1) {
(self.searchBar.value(forKey: "cancelButton") as! UIButton).isEnabled = true
}
```
From: <http://www.jianshu.com/p/a4cfdcf0f7e1>
在日常工作中对于UISearchBar的操作主要集中在:
* 设置UISearchBar中textfiled的边框及圆角
* 设置占位文字的大小及颜色
* 设置输入文字的大小及颜色
* 修改搜索图标
* 修改取消按钮的文本
* ....
实现的方式有很多,就设置边框而言:可以设置背景图片实现效果;或者直接用UITextField来代替UISearchBar等等。但是以上的操作主要是集中在UISearchBar内部的UITextField上,因此获取到UISearchBar内部的UITextField便可以实现以上的效果:
* 通过KVC获取子视图
UISearchBar *searchBar = [[UISearchBar alloc]init];
// 获取内部子视图
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
UIView *backgroundView = [searchBar valueForKey:@"_background"];
UIButton *cancelButton = [searchBar valueForKey:@"_cancelButton"];
* 改变输入框文本
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
// 设置输入文字的大小及颜色
searchField.font = font(12);
searchField.textColor = UIColorRgb(32,32,32);
// 设置占位文字的大小及颜色
[searchField setValue:UIColorRgb(197,197,197) forKeyPath:@"_placeholderLabel.textColor"];
* 设置输入框边框及圆角
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
// 设置边框及圆角
searchField.layer.cornerRadius = 4.0f;
searchField.layer.masksToBounds = YES;
searchField.layer.borderWidth = 0.5f;
searchField.layer.borderColor = UIColorRgbAlpha(95,96,108,0.2).CGColor;
* 设置输入框内搜索图标
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
// 设置searchField上的搜索图标
UIImage *image = [UIImage imageNamed:@"search"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
iView.frame = CGRectMake(0, 0, 15, 15);
searchField.leftView = iView;
* 改变取消按钮的title
UIButton*cancelButton = [searchBar valueForKey:@"_cancelButton"];
[cancelButton setTitle:@"Close"forState:UIControlStateNormal];
---
KVC或者textField的clear属性
```
UIButton *button = [textField valueForKey:@"_clearButton"];
[button setImage:[UIImage imageNamed:@"icon_blueclear"] forState:UIControlStateNormal];
field.clearButtonMode = UITextFieldViewModeWhileEditing;
//swift 3
let clearBtn = self.textField.value(forKey: "_clearButton") as! UIButton
clearBtn.setImage(UIImage(named:"sy-ss"), for: UIControlState.normal)
clearBtn.setImage(UIImage(named:"sy-ss"), for: UIControlState.highlighted)

Author

陈昭

Posted on

2017-08-05

Updated on

2021-12-27

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Kommentare

You forgot to set the shortname for Disqus. Please set it in _config.yml.