问题描述
我有一个3 UITextField
,并设置了占位符文本。在其中一个 UITextField
我希望占位符文本为红色。
I have a 3 UITextField
with placeholder text set. On one of the UITextField
I want the placeholder text to be red.
现在谷歌搜索后,最好的方法是将UITextField子类化并覆盖 drawPlaceholderInRect
。
Now after googling it seems the best way to do this is to subclass UITextField and override drawPlaceholderInRect
.
如何进行子类化和覆盖 drawPlaceholderInRect
?我没有找到任何代码示例或教程,我是Objective-c和iOS开发的新手,所以发现它很难解决。
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.
答案:
创建一个名为 CustomUITextFieldPlaceholder
的新Objective-c类,其子类为的UITextField
。在 CustomUITextFieldPlaceholder.m
中输入以下代码
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
在你的实施中实现上述目的project
To implement the above in your project
#import "CustomUITextFieldPlaceholder.h"
和
IBOutlet CustomUITextFieldPlaceHolder *txtName;
注意:这有效,我相信是正确的做法,但我还没有完全测试过。希望这个例子在我的情况下帮助其他人。
编辑:
已更改
[[UIColor redColor] setFill];
[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];
因此我可以将不透明度设置为70%以模仿默认占位符。
So that I could set the opacity to 70% to mimic default placeholder.
推荐答案
要回答具体问题,这就是子类化的工作原理:
To answer you specific question, this is how subclassing works:
// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
以下是如何覆盖方法:
@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return CGRectMake(x,y,width,height);
}
@end
但我不认为这是你的方法想要覆盖。我认为这就是你要找的东西:
However I don't think that's the method you want to override. I think this is what you're looking for:
@implementation
- (void)drawPlaceholderInRect:(CGRect)rect {
// Your drawing code.
}
@end
这篇关于如何子类化UITextField并覆盖drawPlaceholderInRect以更改占位符颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!