Sunday, June 2, 2013

UITextField textColor example in Objective C (iOS).


UITextField textColor

The color of the text.

@property(nonatomic, retain) UIColor *textColor

Discussion of [UITextField textColor]
This property applies to the entire text string. The default value for this property is a black color. The value for the property can only be set to a non-nil value; setting this property to nil raises an exception.[UITextField textColor]

If you are using styled text in iOS 6 or later, assigning a new value to this property causes the text color to be applied to the entirety of the string in the attributedText property. If you want to apply the color to only a portion of the text, create a new attributed string with the desired style information and associate it with the text field.

UITextField textColor example.
@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;
}

Example of [UITextField textColor].
- (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;
}

UITextField textColor example.
//On button action change color to red
-(void)btnAction
{
    // authentication for missing textfields
    if ([textField_firstName.text isEqualToString:@""])
    {
        textField_firstName.textColor=[UIColor redColor];
        textField_firstName.text=@"Enter First Name";
    }
}

// in the delegate method of UITextField change the following
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //match the following string with above string and change the string to empty string on textfield click
    if ([textField_firstName.text isEqualToString:@"Enter First Name" ])
    {
        textField_firstName.text=@"";
    }

    //change back to the text color you use
    textField_firstName.textColor=[UIColor blackColor];
}

End of UITextField textColor example article.