Change of UITextField placeholder color

后端 未结 13 1760
别跟我提以往
别跟我提以往 2021-01-30 06:09

How to dynamically change placeholder color of the UITextField? This is always the same system color.

No option in xib editor.

13条回答
  •  Happy的楠姐
    2021-01-30 06:52

    From Docs

    @property(nonatomic, copy) NSAttributedString *attributedPlaceholder

    This property is nil by default. If set, the placeholder string is drawn using a 70% grey color and the remaining style information (except the text color) of the attributed string. Assigning a new value to this property also replaces the value of the placeholder property with the same string data, albeit without any formatting information. Assigning a new value to this property does not affect any other style-related properties of the text field.

    Objective-C

    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Some Text" attributes:@{ NSForegroundColorAttributeName : [UIColor redColor] }];
    self.myTextField.attributedPlaceholder = str;
    

    Swift

    let str = NSAttributedString(string: "Text", attributes: [NSForegroundColorAttributeName:UIColor.redColor()])
    myTextField.attributedPlaceholder = str
    

    Swift 4

    let str = NSAttributedString(string: "Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
    myTextField.attributedPlaceholder = str
    

提交回复
热议问题