有时,uitextfield自带的占位文字的颜色太浅或者不满足需求,所以需要修改,而uitextfield没有直接的属性去修改占位文字的颜色,所以只能通过其他间接方式去修改。
例如:系统默认的占位文字颜色太浅
核心代码
方法一:通过attributedplaceholder属性修改占位文字颜色
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
cgfloat viewwidth = self.view.bounds.size.width;
cgfloat textfieldx = 50;
cgfloat textfieldh = 30;
cgfloat padding = 30;
uitextfield *textfield = [[uitextfield alloc] init];
textfield.frame = cgrectmake(textfieldx, 100, viewwidth - 2 * textfieldx, textfieldh);
textfield.borderstyle = uitextborderstyleroundedrect; // 边框类型
textfield.font = [uifont systemfontofsize:14];
nsattributedstring *attrstring = [[nsattributedstring alloc] initwithstring:@"请输入占位文字" attributes:
@{nsforegroundcolorattributename:[uicolor redcolor],
nsfontattributename:textfield.font
}];
textfield.attributedplaceholder = attrstring;
[self.view addsubview:textfield];
|
方法二:通过kvc修改占位文字颜色
?
|
1
2
3
4
5
6
7
8
|
uitextfield *textfield1 = [[uitextfield alloc] init];
textfield1.frame = cgrectmake(textfieldx, cgrectgetmaxy(textfield.frame) + padding, viewwidth - 2 * textfieldx, textfieldh);
textfield1.borderstyle = uitextborderstyleroundedrect;
textfield1.placeholder = @"请输入占位文字";
textfield1.font = [uifont systemfontofsize:14];
// "通过kvc修改占位文字的颜色"
[textfield1 setvalue:[uicolor greencolor] forkeypath:@"_placeholderlabel.textcolor"];
[self.view addsubview:textfield1];
|
方法三:通过重写uitextfield的drawplaceholderinrect:方法修改占位文字颜色
1、自定义一个textfield继承自uitextfield
2、重写drawplaceholderinrect:方法
3、在drawplaceholderinrect方法中设置placeholder的属性
?
|
1
2
3
4
5
6
7
8
9
10
|
// 重写此方法
-(void)drawplaceholderinrect:(cgrect)rect {
// 计算占位文字的 size
cgsize placeholdersize = [self.placeholder sizewithattributes:
@{nsfontattributename : self.font}];
[self.placeholder drawinrect:cgrectmake(0, (rect.size.height - placeholdersize.height)/2, rect.size.width, rect.size.height) withattributes:
@{nsforegroundcolorattributename : [uicolor bluecolor],
nsfontattributename : self.font}];
}
|
总结:
1、当我们使用纯代码创建uitextfield时,用第二种方法(kvc)修改占位文字颜色是最便捷的
2、当我们使用xib或者storyboard创建uitextfield时,通过自定义uitextfield,修改占位文字颜色是最适合的。
3、我们也可以在第三种重写方法中,通过结合第二种方法中的kvc修改属性来实现
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
相关文章
猜你喜欢
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 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 84
-
2025-05-25 60
-
2025-05-25 114
-
2025-05-26 45
-
2025-05-27 85
热门评论



