iPhone UITextField -改变占位符文本颜色

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

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

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

- (void)drawPlaceholderInRect:(CGRect)rect

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

378829 次浏览

也许你想尝试这种方式,但苹果可能会警告你访问私有ivar:

[self.myTextField setValue:[UIColor darkGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
< p > # EYZ0 < br > 根据Martin的说法,这不再适用于iOS 7 Alléus

重写drawPlaceholderInRect:是正确的方法,但由于API(或文档)中的错误,它不起作用。

该方法永远不会在UITextField上被调用。

参见没有调用UITextField上的drawTextInRect

你可以使用digdog的解决方案。因为我不确定这是否通过了苹果的审查,我选择了一个不同的解决方案:用我自己的标签覆盖文本字段,模仿占位符行为。

这有点乱。 代码看起来像这样(注意我在TextField的子类中这样做):

@implementation PlaceholderChangingTextField


- (void) changePlaceholderColor:(UIColor*)color
{
// Need to place the overlay placeholder exactly above the original placeholder
UILabel *overlayPlaceholderLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.frame.origin.x + 8, self.frame.origin.y + 4, self.frame.size.width - 16, self.frame.size.height - 8)] autorelease];
overlayPlaceholderLabel.backgroundColor = [UIColor whiteColor];
overlayPlaceholderLabel.opaque = YES;
overlayPlaceholderLabel.text = self.placeholder;
overlayPlaceholderLabel.textColor = color;
overlayPlaceholderLabel.font = self.font;
// Need to add it to the superview, as otherwise we cannot overlay the buildin text label.
[self.superview addSubview:overlayPlaceholderLabel];
self.placeholder = nil;
}

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

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

另一个不需要子类化的选项-留空占位符,并将标签放在编辑按钮的顶部。管理标签就像你会管理占位符(清除一旦用户输入任何东西..)

我建议另一种解决办法。由于占位符文本使用文本字段的默认字体设置,只需将初始字体颜色设置为您想要的占位符字体颜色。然后设置你的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;
}

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

< p >欢呼, 安卡< / p >

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

自从ios6在UIViews中引入了带属性字符串,就可以像这样为占位符文本分配颜色:

if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
// TODO: Add fall-back code to set placeholder color.
}

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

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

- (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];
}

对于那些使用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);
}
}

我能做的最好的iOS7和更少的是:

- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}


- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}


- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = CGRectInset(bounds, 0, 6); //TODO: can be improved by comparing font size versus bounds.size.height
return rect;
}


- (void)drawPlaceholderInRect:(CGRect)rect {
UIColor *color =RGBColor(65, 65, 65);
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
[self.placeholder drawInRect:rect withAttributes:@{NSFontAttributeName:self.font, UITextAttributeTextColor:color}];
} else {
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font];
}
}

iOS 6及后续版本在UITextField上提供attributedPlaceholder。 iOS 3.2及更高版本在NSMutableAttributedString上提供setAttributes:range:

您可以执行以下操作:

NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:self.yourInput.placeholder];
UIFont *placeholderFont = self.yourInput.font;
NSRange fullRange = NSMakeRange(0, ms.length);
NSDictionary *newProps = @{NSForegroundColorAttributeName:[UIColor yourColor], NSFontAttributeName:placeholderFont};
[ms setAttributes:newProps range:fullRange];
self.yourInput.attributedPlaceholder = ms;

在iOS7中处理垂直和水平对齐以及占位符的颜色。drawwinrect和drawAtPoint不再使用当前上下文的fillColor。

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html

Obj-C

@interface CustomPlaceHolderTextColorTextField : UITextField


@end




@implementation CustomPlaceHolderTextColorTextField : UITextField




-(void) drawPlaceholderInRect:(CGRect)rect  {
if (self.placeholder) {
// color of placeholder text
UIColor *placeHolderTextColor = [UIColor redColor];


CGSize drawSize = [self.placeholder sizeWithAttributes:[NSDictionary dictionaryWithObject:self.font forKey:NSFontAttributeName]];
CGRect drawRect = rect;


// verticially align text
drawRect.origin.y = (rect.size.height - drawSize.height) * 0.5;


// set alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = self.textAlignment;


// dictionary of attributes, font, paragraphstyle, and color
NSDictionary *drawAttributes = @{NSFontAttributeName: self.font,
NSParagraphStyleAttributeName : paragraphStyle,
NSForegroundColorAttributeName : placeHolderTextColor};




// draw
[self.placeholder drawInRect:drawRect withAttributes:drawAttributes];
}
}


@end

你可以改变占位符文本颜色的任何颜色,你想通过使用下面的代码。

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];

为什么不使用UIAppearance方法:

[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];

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

_placeholderLabel.textColor

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

.

[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];

以下仅适用于iOS6+系统(如Alexander W的评论所示):

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:@"Full Name"
attributes:@{NSForegroundColorAttributeName:color}];

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


#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

迅速:

if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}

在Swift 4.0中:

if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}

适用于iOS 6.0 +

[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];

希望能有所帮助。

# EYZ0 # EYZ1

这适用于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])

我已经遇到过这个问题了。在我的情况下,以下代码是正确的。

Objective - C

[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

Swift 4。X

tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")

适用于iOS 13 Swift Code

tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

你也可以使用下面的代码iOS 13

let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red

霍普,这个也许能帮到你。

同样在你的故事板中,没有一行代码

enter image description here

有了这个,我们可以在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"];

对于设置属性文本字段占位符与多种颜色,

只要指定文本,

  //txtServiceText is your Textfield
_txtServiceText.placeholder=@"Badal/ Shah";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:_txtServiceText.placeholder];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor whiteColor] range:[_txtServiceText.placeholder rangeOfString:@"Badal/"]]; //Replace it with your first color Text
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor orangeColor] range:[_txtServiceText.placeholder rangeOfString:@"Shah"]]; // Replace it with your secondcolor string.
_txtServiceText.attributedPlaceholder=mutable;

输出:

enter image description here

斯威夫特的版本。也许能帮到别人。

class TextField: UITextField {
override var placeholder: String? {
didSet {
let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
self.attributedPlaceholder = placeholderString
}
}
}
Xamarin的< p >。iOS开发者,我从这个文档中找到的 # EYZ0 < / p >
textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor =  UIColor.Red });

Swift 3.0 +故事板

为了改变故事板中的占位符颜色,使用next代码创建一个扩展。(如果您认为可以更新此代码,可以更清晰、更安全)。

extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
guard let currentAttributedPlaceholderColor = attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor else { return UIColor.clear }
return currentAttributedPlaceholderColor
}
set {
guard let currentAttributedString = attributedPlaceholder else { return }
let attributes = [NSForegroundColorAttributeName : newValue]


attributedPlaceholder = NSAttributedString(string: currentAttributedString.string, attributes: attributes)
}
}
}

enter image description here

Swift 4版本

extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedStringKey: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}

Swift 5版本

extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedString.Key: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}

# EYZ0

import UIKit


let TEXTFIELD_BLUE  = UIColor.blue
let TEXTFIELD_GRAY  = UIColor.gray


class DBTextField: UITextField {
/// Tetxfield Placeholder Color
@IBInspectable var palceHolderColor: UIColor = TEXTFIELD_GRAY
func setupTextField () {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "",
attributes:[NSForegroundColorAttributeName: palceHolderColor])
}
}


class DBLocalizedTextField : UITextField {
override func awakeFromNib() {
super.awakeFromNib()
self.placeholder = self.placeholder
}
}

在swift 3中。X < / em >

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

in swift 5

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

此解决方案适用于Swift 4.1

    textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])

小心谨慎。

let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.someColor ]
let placeHolderString = NSAttributedString(string: "DON'T_DELETE", attributes: attributes)
txtField.attributedPlaceholder = placeHolderString

需要注意的是,您必须输入非空的String,其中"DON'T_DELETE"是,即使该字符串在其他地方的代码中设置。也许能帮你省下五分钟的脑筋。

  • 如果子类化,你必须做layoutSubviews(不是在init)

  • 奇怪的是你不需要清除正常的placeholder。如果你使用带属性的占位符,它知道不画placeholder