简体   繁体   English

如何子类 UITextField 并覆盖 drawPlaceholderInRect 以更改占位符颜色

[英]How do I subclass UITextField and override drawPlaceholderInRect to change Placeholder color

I have a 3 UITextField with placeholder text set.我有一个带有占位符文本集的 3 UITextField On one of the UITextField I want the placeholder text to be red.UITextField之一上,我希望占位符文本为红色。

Now after googling it seems the best way to do this is to subclass UITextField and override drawPlaceholderInRect .现在在谷歌搜索之后,似乎最好的方法是继承 UITextField 并覆盖drawPlaceholderInRect

How do I go about subclassing and overriding drawPlaceholderInRect ?我如何 go 关于子类化和覆盖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.我没有找到任何代码示例或教程,而且我是 objective-c 和 iOS 开发的新手,所以发现它很难解决。

Answer:回答:

Created a new objective-c class called CustomUITextFieldPlaceholder which subclassed UITextField .创建了一个名为CustomUITextFieldPlaceholder的新 objective-c class ,它是UITextField的子类。 In CustomUITextFieldPlaceholder.m put the following codeCustomUITextFieldPlaceholder.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

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.这样我就可以将不透明度设置为 70% 以模仿默认占位符。

To answer you specific question, this is how subclassing works:为了回答您的具体问题,这是子类化的工作方式:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end

Here's how to override the method:以下是如何覆盖该方法:

@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
[yourTextfield setValue:[UIColor colorWithRed:62.0/255.0f green:62.0/255.0f blue:62./255.0f alpha:1.0f]  forKeyPath:@"_placeholderLabel.textColor"];

I guess this would be helpful我想这会有所帮助

Subclassing won't change the color.子类化不会改变颜色。 I have put forward a work around here.我在这里提出了一项工作。

UITextField placeholder font color white iOS 5? UITextField 占位符字体颜色 白色 iOS 5?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM