iOS改变UITextField占位文字颜色的三种方法

2025-05-29 0 87

有时,uitextfield自带的占位文字的颜色太浅或者不满足需求,所以需要修改,而uitextfield没有直接的属性去修改占位文字的颜色,所以只能通过其他间接方式去修改。

例如:系统默认的占位文字颜色太浅

iOS改变UITextField占位文字颜色的三种方法

需要加深颜色,或者改变颜色
示例:

iOS改变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。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS改变UITextField占位文字颜色的三种方法 https://www.kuaiidc.com/90808.html

相关文章

发表评论
暂无评论