【发布时间】:2011-09-03 08:02:05
【问题描述】:
我有一个带有占位符文本集的 3 UITextField。在UITextField 之一上,我希望占位符文本为红色。
现在在谷歌搜索之后,似乎最好的方法是继承 UITextField 并覆盖 drawPlaceholderInRect。
如何继承和覆盖drawPlaceholderInRect?我没有找到任何代码示例或教程,而且我是 Objective-c 和 iOS 开发的新手,所以发现它很难解决。
答案:
创建了一个名为CustomUITextFieldPlaceholder 的新objective-c 类,它是UITextField 的子类。在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"
和
IBOutlet CustomUITextFieldPlaceHolder *txtName;
注意:这行得通,我相信这是正确的做法,但我还没有完全测试过。希望这个例子可以帮助我遇到的其他人。
编辑:
改变了
[[UIColor redColor] setFill];
为
[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];
这样我就可以将不透明度设置为 70% 以模仿默认占位符。
【问题讨论】:
-
子类化和覆盖该方法不会帮助您更改字体颜色,它只是让您自定义占位符的显示位置。
-
也许你可以尝试覆盖这个委托方法 -
(void)drawPlaceholderInRect:(CGRect)rect
标签: iphone objective-c ios uitextfield subclass