2011-05-27 63 views
17

我有一个3 UITextField,其中包含占位符文本集。在其中一个UITextField我希望占位符文本为红色。如何继承UITextField并覆盖drawPlaceholderInRect以更改占位符颜色

现在谷歌搜索后,似乎做到这一点的最好方法是继承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%,以模仿默认占位符。

+0

子类并重写该方法不会帮助你改变字体颜色,它只是让你自定义显示的占位符在哪里。 – 2011-05-27 11:23:05

+0

也许你可以尝试覆盖这个委托方法 - '(void)drawPlaceholderInRect:(CGRect)rect' – Hisenberg 2011-05-27 11:27:52

回答

7

要回答你的具体问题,这是子类是如何工作的:

// 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 
+0

感谢您的回复@Erik,您的权利我的意思是drawPlaceholderInRect。我将创建代码来做到这一点,手指划过:) – 2011-05-27 11:52:49

+0

但创建类后,在实现中添加此方法我无法获得我的文本字段占位符颜色的变化 – 2016-04-05 05:55:47

0
[yourTextfield setValue:[UIColor colorWithRed:62.0/255.0f green:62.0/255.0f blue:62./255.0f alpha:1.0f] forKeyPath:@"_placeholderLabel.textColor"]; 

我想这将是有益的

+0

该下划线使它看起来很私密... – 2013-05-23 08:02:12