我有一个 3UITextField
与占位符文本集。在其中之一UITextField
我希望占位符文本为红色。
现在,在谷歌搜索之后,似乎最好的方法是子类化 UITextField 并覆盖drawPlaceholderInRect
.
我如何进行子类化和重写drawPlaceholderInRect
?我还没有找到任何关于此的代码示例或教程,而且我是 Objective-C 和 iOS 开发的新手,所以发现解决这个问题很棘手。
Answer:
创建了一个新的 Objective-C 类,名为CustomUITextFieldPlaceholder
哪个子类UITextField
. In CustomUITextFieldPlaceholder.m
输入以下代码
@implementation CustomUITextFieldPlaceholder
- (void)drawPlaceholderInRect:(CGRect)rect {
// Set colour and font size of placeholder text
[[UIColor redColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];
}
@end
在您的项目中实现上述内容
#import "CustomUITextFieldPlaceholder.h"
and
IBOutlet CustomUITextFieldPlaceHolder *txtName;
注意:这是可行的,我相信这是正确的做法,但我还没有完全测试它。希望这个例子对其他处于我的情况的人有所帮助。
Edit:
Changed
[[UIColor redColor] setFill];
for
[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];
这样我就可以将不透明度设置为 70% 以模仿默认占位符。