Sunday, June 2, 2013

UITextField attributedPlaceholder example in Objective C (iOS).


UITextField attributedPlaceholder

The styled string that is displayed when there is no other text in the text field.

@property(nonatomic,copy) NSAttributedString *attributedPlaceholder

Discussion of [UITextField 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.

UITextField attributedPlaceholder example.
Since the introduction of attributed strings in UIViews in iOS 6, it's possible to assign a color to the placeholder text like this:

UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];

Example of [UITextField attributedPlaceholder].
    UIColor *color = [UIColor blackColor];
    UIFont* boldFont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
    [self.textField setFont:boldFont];
    self.textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Test" attributes:@{NSForegroundColorAttributeName: color}];

End of UITextField attributedPlaceholder example article.