如何子类化 UITextField 并重写 drawPlaceholderInRect 以更改占位符颜色
我有一个 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% 以模仿默认占位符。
I have a 3 UITextField
with placeholder text set. On one of the UITextField
I want the placeholder text to be red.
Now after googling it seems the best way to do this is to subclass UITextField and override drawPlaceholderInRect
.
How do I go about subclassing and overriding drawPlaceholderInRect
? I've not found any code examples or tutorials on this and I'm new to objective-c and iOS development so finding it tricky to work it out.
Answer:
Created a new objective-c class called CustomUITextFieldPlaceholder
which subclassed UITextField
. In CustomUITextFieldPlaceholder.m
put the following code
@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
To implement the above in your project
#import "CustomUITextFieldPlaceholder.h"
and
IBOutlet CustomUITextFieldPlaceHolder *txtName;
Note: This works and I believe is correct practice, however I have not fully tested it. Hope this example helps others in my situation.
Edit:
Changed
[[UIColor redColor] setFill];
for
[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];
So that I could set the opacity to 70% to mimic default placeholder.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想这会有帮助
I guess this would be helpful
为了回答您的具体问题,这就是子类化的工作原理:
以下是如何重写该方法:
但是我不认为这是您想要重写的方法。我认为这就是您正在寻找的:
To answer you specific question, this is how subclassing works:
Here's how to override the method:
However I don't think that's the method you want to override. I think this is what you're looking for:
子类化不会改变颜色。我在这里提出了一项工作。
UITextField 占位符字体颜色白色 iOS 5?
Subclassing won't change the color. I have put forward a work around here.
UITextField placeholder font color white iOS 5?