【问题标题】:How do I subclass UITextField and override drawPlaceholderInRect to change Placeholder color如何子类化 UITextField 并覆盖 drawPlaceholderInRect 以更改占位符颜色
【发布时间】:2011-09-03 08:02:05
【问题描述】:

我有一个带有占位符文本集的 3 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"

IBOutlet CustomUITextFieldPlaceHolder *txtName;

注意:这行得通,我相信这是正确的做法,但我还没有完全测试过。希望这个例子可以帮助我遇到的其他人。

编辑:

改变了

[[UIColor redColor] setFill];

[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];

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

【问题讨论】:

  • 子类化和覆盖该方法不会帮助您更改字体颜色,它只是让您自定义占位符的显示位置。
  • 也许你可以尝试覆盖这个委托方法 - (void)drawPlaceholderInRect:(CGRect)rect

标签: iphone objective-c ios uitextfield subclass


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回复@Erik,您的权利我的意思是drawPlaceholderInRect。我将尝试创建代码来做到这一点,祈祷:)
  • 但在创建类并在实现中添加此方法后,我的文本字段占位符颜色无法更改
【解决方案2】:

子类化不会改变颜色。我在这里提出了一项工作。

UITextField placeholder font color white iOS 5?

【讨论】:

    【解决方案3】:
    [yourTextfield setValue:[UIColor colorWithRed:62.0/255.0f green:62.0/255.0f blue:62./255.0f alpha:1.0f]  forKeyPath:@"_placeholderLabel.textColor"];
    

    我想这会有所帮助

    【讨论】:

      猜你喜欢
      • 2012-04-12
      • 2010-11-23
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 2011-11-11
      • 2014-06-12
      • 2013-09-12
      • 2019-10-09
      相关资源
      最近更新 更多