如何inheritanceUITextField并覆盖drawPlaceholderInRect以更改占位符颜色
我有一个占位符文本设置3 UITextField
。 在其中一个UITextField
我希望占位符文本是红色的。
现在谷歌search后,似乎做到这一点的最好办法是drawPlaceholderInRect
UITextField并覆盖drawPlaceholderInRect
。
我如何去做子类化和重写drawPlaceholderInRect
? 我还没有find任何代码示例或教程,我是新来的Objective-C和iOS开发,所以find了棘手的工作。
回答:
创build了一个名为CustomUITextFieldPlaceholder
的新的Objective-c类,它将子类UITextField
。 在CustomUITextFieldPlaceholder.m
input下面的代码
@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;
注意:这个工作,我相信是正确的做法,但我没有完全testing它。 希望这个例子能帮助别人。
编辑:
变
[[UIColor redColor] setFill];
对于
[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];
所以我可以设置不透明度为70%,以模仿默认的占位符。
为了回答你的具体问题,这是子类化的工作原理:
// CustomTextField.h @interface CustomTextField : UITextField { } @end
以下是如何覆盖该方法:
@implementation - (CGRect)placeholderRectForBounds:(CGRect)bounds { return CGRectMake(x,y,width,height); } @end
不过,我不认为这是你想重写的方法。 我想这是你要找的东西:
@implementation - (void)drawPlaceholderInRect:(CGRect)rect { // Your drawing code. } @end
子类不会改变颜色。 我在这里提出了一个工作。
UITextField占位符字体颜色白色iOS 5?
[yourTextfield setValue:[UIColor colorWithRed:62.0/255.0f green:62.0/255.0f blue:62./255.0f alpha:1.0f] forKeyPath:@"_placeholderLabel.textColor"];
我想这会有所帮助