我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。

我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。

我相信如果我重写这个方法:

- (void)drawPlaceholderInRect:(CGRect)rect

那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。


当前回答

我建议另一种解决办法。由于占位符文本使用文本字段的默认字体设置,只需将初始字体颜色设置为您想要的占位符字体颜色。然后设置你的UITextField的委托并实现以下方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //set color for text input
    textField.textColor = [UIColor blackColor];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    //set color for placeholder text
    textField.textColor = [UIColor redColor];
    return YES;
}

因此,如果用户开始在文本框中输入文本的颜色改变为黑色,在文本框再次被清除后,占位符文本将再次出现红色。

干杯, 安卡

其他回答

对于那些使用Monotouch (Xamarin.iOS)的人,这里是Adam的答案,翻译成c#:

public class MyTextBox : UITextField
{
    public override void DrawPlaceholder(RectangleF rect)
    {
        UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
        new NSString(this.Placeholder).DrawString(rect, Font);
    }
}

我需要保持占位符的对齐,这样亚当的答案对我来说就不够了。

为了解决这个问题,我使用了一个小的变化,我希望也能帮助到你们:

- (void) drawPlaceholderInRect:(CGRect)rect {
    //search field placeholder color
    UIColor* color = [UIColor whiteColor];

    [color setFill];
    [self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}

简单无痛,对一些人来说可能是一个简单的选择。

_placeholderLabel.textColor

不建议制作,Apple可能会拒绝您的提交。

我是xcode的新手,我找到了一种方法来达到同样的效果。

我放置了一个uilabel的位置占位符与所需的格式和隐藏它

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    switch (textField.tag)
    {
        case 0:
            lblUserName.hidden=YES;
            break;

        case 1:
            lblPassword.hidden=YES;
            break;
 
        default:
            break;
    }
}

我同意这是一个工作,而不是一个真正的解决方案,但效果是一样的,从这个链接

注:仍然适用于iOS 7:|

类别增值。可以优化检查有效的颜色变化。


#import <UIKit/UIKit.h>

@interface UITextField (OPConvenience)

@property (strong, nonatomic) UIColor* placeholderColor;

@end

#import "UITextField+OPConvenience.h"

@implementation UITextField (OPConvenience)

- (void) setPlaceholderColor: (UIColor*) color {
    if (color) {
        NSMutableAttributedString* attrString = [self.attributedPlaceholder mutableCopy];
        [attrString setAttributes: @{NSForegroundColorAttributeName: color} range: NSMakeRange(0,  attrString.length)];
        self.attributedPlaceholder =  attrString;
    }
}

- (UIColor*) placeholderColor {
    return [self.attributedPlaceholder attribute: NSForegroundColorAttributeName atIndex: 0 effectiveRange: NULL];
}

@end