Programmatically Add Default UITextField

I haven’t posted anything in a while, but I’ve been programming much more often and figured I’d share some answers to questions that had me stuck for a while. Now, if you’ve ever tried to add a UITextField purely through code you’ve probably noticed that what you get is a blank area that you can double-tap and add text to. When you add it using Interface Builder you get this pretty rectangle with rounded edges – what gives?

Well, I have no idea what gives. But what I do know is how to use a whole bunch of extra code to fix it. Here’s some nicely commented code that shows what I’m talking about:

- (UITextField *)getCustomTextField: (NSString *)placeholderText xLoc:(int)X
                               yLoc:(int)Y width:(int)width height:(int)height
{
    // Start by allocating an ugly default text field
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(X, Y, width, height)];
    
    // Set font to default text field font
    textField.font = [UIFont fontWithName:@"Helvetica Neue" size:14];
    
    // If the man wants some placeholder text, give it to him
    if (placeholderText != nil)
        textField.placeholder = placeholderText;
    
    // Add the clear button while editing
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    // Design our border so it looks like a "real" UITextField
    [textField.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.4] CGColor]];
    [textField.layer setBorderWidth:0.5];
    
    // Make that sexy corner all round
    textField.layer.cornerRadius = 7;
    textField.clipsToBounds = YES;
    
    // Add padding to the box so it looks real
    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 9, 0)];
    textField.leftView = paddingView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    return textField;
}

That method will return a nicely formatted UITextField. It may not look precisely like the one you get from IB, but I challenge you to get it closer. If you don’t want any placeholder text just send nil or edit the method to take no instance variables.

Leave a Reply

Your email address will not be published. Required fields are marked *