582

UITextFieldコントロールで設定したプレースホルダーテキストの色を黒に変更したいと思います。

通常のテキストをプレースホルダーとして使用せず、プレースホルダーの動作を模倣するためにすべてのメソッドをオーバーライドする必要がないように、これを実行したいと思います。

このメソッドをオーバーライドすると、次のようになります。

- (void)drawPlaceholderInRect:(CGRect)rect

その後、私はこれを行うことができるはずです。しかし、このメソッド内から実際のプレースホルダーオブジェクトにアクセスする方法がわかりません。

4

32 に答える 32

817

iOS 6の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.
}
于 2012-12-04T03:08:32.933 に答える
239

簡単で痛みがなく、一部の人にとっては簡単な代替手段になる可能性があります。

_placeholderLabel.textColor

プロダクションには推奨されませんが、Appleはあなたの提出を拒否する場合があります。

于 2014-02-25T14:28:30.490 に答える
195

そのようにオーバーライドdrawPlaceholderInRect:(CGRect)rectして、プレースホルダーテキストを手動でレンダリングできます。

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
于 2010-08-03T11:35:41.457 に答える
175

以下のコードを使用して、プレースホルダーのテキストの色を任意の色に変更できます。

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
于 2013-11-08T06:18:30.913 に答える
172

これはSwift<3.0で機能します。

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

iOS8.2およびiOS8.3ベータ4でテスト済み。

スウィフト3:

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

スウィフト4:

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

Swift 4.2:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
于 2015-01-06T11:50:51.923 に答える
158

この方法を試してみたいと思うかもしれませんが、Appleはプライベートivarへのアクセスについて警告する場合があります。

[self.myTextField setValue:[UIColor darkGrayColor] 
                forKeyPath:@"_placeholderLabel.textColor"];


MartinAlléusによると、これはiOS7では機能しなくなりました。

于 2010-01-04T07:53:52.087 に答える
84

Swift3.0+ストーリーボード

ストーリーボードのプレースホルダーの色を変更するには、次のコードで拡張機能を作成します。(このコードを自由に更新してください。考えれば、より明確で安全になります)。

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)
        }
    }
}

ここに画像の説明を入力してください

Swift4バージョン

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)
        }
    }
}

Swift5バージョン

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)
        }
    }
}
于 2017-05-21T12:05:16.787 に答える
77

Swiftの場合:

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])
}
于 2014-12-11T16:22:48.530 に答える
43

以下はiOS6+でのみ(Alexander Wのコメントに示されているように):

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
   [[NSAttributedString alloc]
       initWithString:@"Full Name"
       attributes:@{NSForegroundColorAttributeName:color}];
于 2014-05-19T06:33:28.037 に答える
36

私はすでにこの問題に直面していました。私の場合、以下のコードは正しいです。

Objective C

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

Swift4.Xの場合

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

iOS13Swiftコードの場合

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

iOS13用に以下のコードを使用することもできます

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

うまくいけば、これはあなたを助けるかもしれません。

于 2015-06-20T13:20:14.970 に答える
32

これにより、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"];
于 2016-02-12T07:30:44.607 に答える
24

迅速な3.Xで

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

迅速な5で

textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
于 2018-01-01T06:25:23.057 に答える
22

メソッドを使用してみませんかUIAppearance

[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
于 2013-12-19T13:08:53.787 に答える
18

ストーリーボードでも、1行のコードなしで

ここに画像の説明を入力してください

于 2016-02-05T10:00:44.527 に答える
12

iOS6.0以降の場合

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

それが役に立てば幸い。

注: プライベートAPIにアクセスしているため、Appleはアプリを拒否する場合があります(0.01%の可能性)。私は2年前からすべてのプロジェクトでこれを使用していますが、Appleはこれを要求しませんでした。

于 2014-12-30T06:48:33.897 に答える
10

Xamarin.iOS開発者の場合、このドキュメント https://developer.xamarin.com/api/type/Foundation.NSAttributedString/から見つけました。

textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor =  UIColor.Red });
于 2016-12-07T11:59:25.387 に答える
9

Swiftバージョン。おそらくそれは誰かを助けるでしょう。

class TextField: UITextField {
   override var placeholder: String? {
        didSet {
            let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
            self.attributedPlaceholder = placeholderString
        }
    }
}
于 2016-08-29T10:05:15.970 に答える
8

iOS6以降はで提供attributedPlaceholderしていますUITextField。iOS3.2以降はで提供setAttributes:range:していますNSMutableAttributedString

次のことができます。

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;
于 2013-10-02T01:21:02.900 に答える
7

Swift4.1用のこのソリューション

    textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
于 2018-10-10T09:54:48.337 に答える
6

iOS7でプレースホルダーの色だけでなく、垂直方向と水平方向の両方の配置を処理します。drawInRectと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
于 2013-11-02T15:22:57.353 に答える
6

カテゴリFTW。効果的な色の変化をチェックするために最適化できます。


#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
于 2014-05-27T20:35:19.467 に答える
6

Swift 5WITHCAVEAT。

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

String注意点は、その文字列が他の場所のコードで設定されている場合でも、「DON'T_DELETE」がある場所に空でないものを入力する必要があるということです。頭を悩ませるのに5分節約できるかもしれません。

于 2019-10-31T02:00:36.850 に答える
4

オーバーライドdrawPlaceholderInRect:は正しい方法ですが、API(またはドキュメント)のバグのために機能しません。

メソッドがで呼び出されることはありませんUITextField

呼び出されないUITextFieldのdrawTextInRectも参照してください。

あなたはdigdogの解決策を使うかもしれません。それがAppleのレビューを通過するかどうかわからないので、私は別の解決策を選択しました。プレースホルダーの動作を模倣する独自のラベルでテキストフィールドをオーバーレイします。

ただし、これは少し面倒です。コードは次のようになります(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;
}
于 2010-04-06T00:03:32.370 に答える
3

Iamは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でも引き続き機能します:|

于 2012-05-23T09:14:32.560 に答える
2

Monotouch(Xamarin.iOS)を使用している場合は、C#に翻訳されたAdamの回答を次に示します。

public class MyTextBox : UITextField
{
    public override void DrawPlaceholder(RectangleF rect)
    {
        UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
        new NSString(this.Placeholder).DrawString(rect, Font);
    }
}
于 2013-09-18T17:15:15.347 に答える
2

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];
  }
}
于 2013-09-25T07:02:26.547 に答える
2

複数の色の属性付きテキストフィールドプレースホルダーを設定する場合、

テキストを指定するだけです。

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

出力:-

ここに画像の説明を入力してください

于 2016-05-20T05:52:29.320 に答える
1

プレースホルダーの配置を維持する必要があったので、アダムの答えは私には十分ではありませんでした。

これを解決するために、私はあなたの何人かにも役立つことを願っている小さなバリエーションを使用しました:

- (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];
}
于 2013-06-10T10:13:56.523 に答える
1
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
于 2014-04-23T09:34:04.623 に答える
0

サブクラス化を必要としない別のオプション-プレースホルダーを空白のままにし、編集ボタンの上にラベルを配置します。プレースホルダーを管理するのと同じようにラベルを管理します(ユーザーが何かを入力するとクリアされます。)

于 2010-12-06T22:34:28.823 に答える
0

Swift3では

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
    }
}
于 2017-12-07T05:38:28.790 に答える
-10

別の解決策を提案します。プレースホルダーテキストはテキストフィールドのデフォルトのフォント設定を使用するため、初期フォントの色を目的のプレースホルダーフォントの色に設定するだけです。次に、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;
}

したがって、ユーザーがテキストフィールドに入力を開始すると、テキストの色が黒に変わり、テキストフィールドが再びクリアされた後、プレースホルダーテキストが再び赤で表示されます。

乾杯、別名

于 2011-08-09T21:00:31.407 に答える