uitextfield是ios开发中用户交互中重要的一个控件,常被用来做账号密码框,输入信息框等。
观察效果图
uitextfield有以下几种特点:
1.默认占位文字是灰色的
2.当光标点上去时,占位文字变为白色
3.光标是白色的
接下来我们通过不同的方法来解决问题
一.将xib中的uitextfield与代码关联
?
|
1
2
3
4
5
6
7
8
9
10
11
|
通过nsattributestring方法来更改占位文字的属性
(void)viewdidload {
[super viewdidload];
// do any additional setup after loading the view from its nib.
//文字属性
nsmutabledictionary *dict = [nsmutabledictionary dictionary];
dict[nsforegroundcolorattributename] = [uicolor graycolor];
//带有属性的文字(富文本属性)nsattributestring
nsattributedstring *attr = [[nsattributedstring alloc] initwithstring:@"手机号" attributes:dict];
self.phonefield.attributedplaceholder = attr;
}
|
但是这种方法只能做出第一种效果,而且不具有通用性。
二.自定义一个uitextfield的类
重写它的drawplaceholderinrect方法
?
|
1
2
3
4
5
6
|
//画出占位文字- (void)drawplaceholderinrect:(cgrect)rect {
[self.placeholder drawinrect:cgrectmake(0, 13, self.size.width, 25) withattributes:@{
nsforegroundcolorattributename : [uicolor graycolor],
nsfontattributename : [uifont systemfontofsize:14]
}];
}
|
这个方法和上一个方法类似,只能做出第一种效果,但这个具有通用性
三.利用runtime运行时机制
runtime是官方的一套c语言库
能做出很多底层的操作(比如访问隐藏的一些成员变量\\成员方法)
?
|
1
2
3
4
5
6
7
8
9
10
|
(void)initialize {
unsigned int count = 0;
ivar *ivars = class_copyivarlist([uitextfield class] , &count);
for (int i = 0; i < count; i++) {
//取出成员变量
ivar ivar = *(ivars + i);
//打印成员变量名字
ddzlog(@"%s",ivar_getname(ivar));
}
}
|
利用class_copyivarlist这个c函数,将所有的成员变量打印出来
这样我们就可以直接通过kvc进行属性设置了
?
|
1
2
3
4
5
|
- (void)awakefromnib {
//修改占位文字颜色
[self setvalue:[uicolor graycolor] forkeypath:@"_placeholderlabel.textcolor"]; //设置光标颜色和文字颜色一致
self.tintcolor = self.textcolor;
}
|
通过这个方法可以完成所有的效果,既具有通用性也简单
最后一个效果是
在获得焦点时改变占位文字颜色
在失去焦点时再改回去
?
|
1
2
3
4
5
6
7
8
9
10
|
//获得焦点时
- (bool)becomefirstresponder {
//改变占位文字颜色
[self setvalue:self.textcolor forkeypath:@"_placeholderlabel.textcolor"]; return [super becomefirstresponder];
}
//失去焦点时
- (bool)resignfirstresponder {
//改变占位文字颜色
[self setvalue:[uicolor graycolor] forkeypath:@"_placeholderlabel.textcolor"]; return [super resignfirstresponder];
}
|
相关文章
猜你喜欢
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 32
-
2025-06-05 33
-
2025-06-04 102
-
2025-05-25 36
-
Ubuntu 16.04与Apache虚拟主机配置的步骤详解
2025-05-25 90
热门评论



