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

Mat*_*ice 17 iphone subclass objective-c uitextfield ios

我有一个UITextField带占位符文本集的3 .其中一个UITextField我希望占位符文本为红色.

现在谷歌搜索后,似乎最好的方法是子类UITextField和覆盖drawPlaceholderInRect.

我如何进行子类化和重写drawPlaceholderInRect?我没有找到任何代码示例或教程,我是Objective-c和iOS开发的新手,所以发现它很难解决.

回答:

创建了一个新的objective-c类,称为CustomUITextFieldPlaceholder子类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
Run Code Online (Sandbox Code Playgroud)

在您的项目中实现上述内容

#import "CustomUITextFieldPlaceholder.h"
Run Code Online (Sandbox Code Playgroud)

IBOutlet CustomUITextFieldPlaceHolder *txtName;
Run Code Online (Sandbox Code Playgroud)

注意:这是有效的,我相信是正确的做法,但我还没有完全测试它.希望这个例子在我的情况下帮助其他人.

编辑:

[[UIColor redColor] setFill];
Run Code Online (Sandbox Code Playgroud)

对于

[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];
Run Code Online (Sandbox Code Playgroud)

这样我就可以将不透明度设置为70%来模仿默认占位符.

Eri*_*k B 8

为了回答您的具体问题,这是子类化的工作原理:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
Run Code Online (Sandbox Code Playgroud)

以下是如何覆盖该方法:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);
}
@end
Run Code Online (Sandbox Code Playgroud)

但是我不认为这是你要覆盖的方法.我想这就是你要找的东西:

@implementation
- (void)drawPlaceholderInRect:(CGRect)rect {
    // Your drawing code.
}
@end
Run Code Online (Sandbox Code Playgroud)