Iphone 如何将UITextField子类化并覆盖DrawPlaceholdinRect以更改占位符颜色
我有一个带有占位符文本集的3Iphone 如何将UITextField子类化并覆盖DrawPlaceholdinRect以更改占位符颜色,iphone,objective-c,ios,uitextfield,subclass,Iphone,Objective C,Ios,Uitextfield,Subclass,我有一个带有占位符文本集的3UITextField。在其中一个UITextField上,我希望占位符文本为红色 现在,在谷歌搜索之后,似乎最好的方法是将UITextField子类化并覆盖drawPlaceholderInRect 如何子类化和重写drawPlaceholderInRect?我还没有找到任何关于这方面的代码示例或教程,而且我是objective-c和iOS开发的新手,因此发现解决这一问题很困难 回答: 创建了一个名为CustomUITextFieldPlaceholder的新obj
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"
及
注意:这是有效的,我相信这是正确的做法,但我还没有完全测试它。希望这个例子能帮助我处境中的其他人。
编辑:
改变
[[UIColor redColor] setFill];
为了
这样我就可以将不透明度设置为70%来模拟默认占位符。为了回答您的特定问题,下面是子类化的工作原理:
// 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
我想这会很有帮助子类化不会改变颜色。我在这里提出了一项工作
子类化和重写该方法不会帮助您更改字体颜色,它只允许您自定义占位符的显示位置。也许您可以尝试重写此委托方法-
(void)drawplaceholdinrect:(CGRect)rect
谢谢您的回复@Erik,您的权利我是指drawplaceholdinrect。我将尝试创建代码来实现这一点,祈祷:)但在创建类并在实现中添加此方法后,我无法更改文本字段占位符的颜色
@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return CGRectMake(x,y,width,height);
}
@end
@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"];