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

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

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

- (void)drawPlaceholderInRect:(CGRect)rect

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


当前回答

这适用于Swift <3.0:

myTextField.attributedPlaceholder = 
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])

在iOS 8.2和iOS 8.3 beta 4中测试。

斯威夫特3:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])

斯威夫特4:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

斯威夫特4.2:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

其他回答

有了这个,我们可以在iOS中改变文本字段占位符文本的颜色

[self.userNameTxt setValue:[UIColor colorWithRed:41.0/255.0 green:91.0/255.0 blue:106.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];

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

_placeholderLabel.textColor

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

你可以重写drawPlaceholderInRect:(CGRect)rect来手动渲染占位符文本:

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}

这适用于Swift <3.0:

myTextField.attributedPlaceholder = 
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])

在iOS 8.2和iOS 8.3 beta 4中测试。

斯威夫特3:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])

斯威夫特4:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

斯威夫特4.2:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

我是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:|