修改UITextField的placeholder字体颜色并垂直居中

本文介绍如何使用KVC来修改UITextField的placeholder字体、颜色及大小,并通过NSParagraphStyle解决字体显示不垂直居中的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

修改字体和颜色需要用到kvc:

yourTextField.placeholder = @"username is in here!";

[yourTextField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

[yourTextField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

有一个问题,当字体过小的时候,placeholder的字体会显示不是垂直居中的,这需要用到NSParagraphStyle,

我的解决办法是:

NSMutableParagraphStyle *style = [yourTextField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];

style.minimumLineHeight = yourTextField.font.lineHeight - (yourTextField.font.lineHeight - [UIFont systemFontOfSize:14.0].lineHeight) / 2.0;

yourTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"YourTextField Placeholder text"

attributes:@{

NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:0.7f],

NSFontAttributeName : [UIFont systemFontOfSize:14.0],

NSParagraphStyleAttributeName : style

}

];

-摘抄

转载于:https://www.cnblogs.com/akiha/p/7086097.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值