Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

UITextField Properties and Usage Guide

Tech 2

UITextField is a fundamental UI component in UIKit for handling text input. This guide details its properties, customization, delegate methods, and practical examples.

Key Properties

1. enablesReturnKeyAutomatically

Defaults to NO. If set to YES, the return key is disabled when the text field is empty.

2. borderStyle

Defines the border appearance using the UITextBorderStyle enum:

textField.borderStyle = UITextBorderStyleRoundedRect; // Options: None, Line, Bezel, RoundedRect

3. backgroundColor

Sets the background color of the text field:

textField.backgroundColor = [UIColor whiteColor];

4. background and disabledBackground

  • background: Backgronud image (only valid when borderStyle is UITextBorderStyleNone):
textField.background = [UIImage imageNamed:@"bg.png"];
  • disabledBackground: Background when the text field is disabled:
textField.disabledBackground = [UIImage imageNamed:@"disabled_bg.png"];

5. placeholder

Dislpays hint text when the field is empty:

textField.placeholder = @"Enter password";

6. font and textColor

  • font: Sets the text font and size:
textField.font = [UIFont fontWithName:@"Arial" size:20.0];
  • textColor: Sets the text color:
textField.textColor = [UIColor redColor];

7. clearButtonMode

Controls when the clear ("X") button appears (enum UITextFieldViewMode):

textField.clearButtonMode = UITextFieldViewModeAlways; // Options: Never, WhileEditing, UnlessEditing, Always

8. secureTextEntry

Hides input (e.g., for passwords):

textField.secureTextEntry = YES;

9. autocorrectionType

Controls auto-correction behavior (enum UITextAutocorrectionType):

textField.autocorrectionType = UITextAutocorrectionTypeNo;

10. clearsOnBeginEditing

Clears existing text when editing starts:

textField.clearsOnBeginEditing = YES;

11. textAlignment and contentVerticalAlignment

  • textAlignment: Aligns text horizontally (.left, .center, .right):
textField.textAlignment = UITextAlignmentLeft;
  • contentVerticalAlignment: Aligns text vertically (inherited from UIControl):
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

12. adjustsFontSizeToFitWidth and minimumFontSize

  • adjustsFontSizeToFitWidth: Shrinks text to fit the field:
textField.adjustsFontSizeToFitWidth = YES;
  • minimumFontSize: Minimum font size when shrinking:
textField.minimumFontSize = 14.0;

13. keyboardType

Configures the keyboard style (enum UIKeyboardType):

textField.keyboardType = UIKeyboardTypeNumberPad; // Options: Default, ASCIICapable, NumbersAndPunctuation, etc.

14. autocapitalizationType

Controls text capitalization (enum UITextAutocapitalizationType):

textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // Options: Words, Sentences, AllCharacters

15. returnKeyType

Customizes the return key (enum UIReturnKeyType):

textField.returnKeyType = UIReturnKeyDone; // Options: Go, Search, Send, etc.

16. delegate

Assign a delegate to handle text field events (conform to UITextFieldDelegate):

textField.delegate = self;

17. rightView and rightViewMode

Add a custom view (e.g., image) to the right:

UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon.png"]];
textField.rightView = iconView;
textField.rightViewMode = UITextFieldViewModeAlways; // Options: Never, WhileEditing, UnlessEditing

Delegate Methods (Conform to UITextFieldDelegate)

Implement these methods to handle text field interactions:

1. textFieldShouldReturn:

Dismiss the keyboard when the return key is pressed:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

2. textFieldShouldBeginEditing:

Allow/deny editing:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES; // Allow editing
}

3. textFieldDidBeginEditing:

Handle actions when editing starts:

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // e.g., Update UI or start animations
}

4. textFieldShouldEndEditing:

Allow/deny ending editing:

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    return YES; // Allow ending editing
}

5. textFieldDidEndEditing:

Handle actions when editing ends:

- (void)textFieldDidEndEditing:(UITextField *)textField {
    // e.g., Validate input or update data
}

6. textField:shouldChangeCharactersInRange:replacementString:

Validate or modify text changes:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacement {
    // Example: Allow only numbers and decimals
    NSString *allowedChars = @"0123456789.";
    NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
    NSString *filtered = [[replacement componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@""];
    if (![replacement isEqualToString:filtered]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Input Error" message:@"Only numbers and decimals are allowed." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    return YES;
}

Notifications

UITextField posts notifications for key events:

  • UITextFieldTextDidBeginEditingNotification
  • UITextFieldTextDidChangeNotification
  • UITextFieldTextDidEndEditingNotification

Subscribe to these notifications to react to text changes:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(textDidChange:) 
                                             name:UITextFieldTextDidChangeNotification 
                                           object:textField];

- (void)textDidChange:(NSNotification *)notification {
    UITextField *field = (UITextField *)notification.object;
    NSLog(@"Text changed: %@", field.text);
}

Storyboard Setup

Configure UITextField in Interface Builder (Storyboard):

  • Text: Default text (e.g., "Hello").
  • Placeholder: Hint text (e.g., "Enter name").
  • Background: Custom background image.
  • Disabled: Prevent user interaction (check to disable).
  • Alignment: Left/center/right text alignment.
  • Border Style: Choose from (None, Line, Bezel, Rounded Rect).
  • Clear Button: When to show the clear ("X") button (Never, While Editing, Unless Editing, Always Visible).
  • Clear on Editing Begins: Clear existing text when editing starts.
  • Text Color: Custom text color.
  • Font: Text font and size.
  • Min Font Size: Minimum font size (used with Adjust to Fit).
  • Adjust to Fit: Shrink text to fit the field.
  • Capitalization: Auto-capitalization style (None, Words, Sentences, All Characters).
  • Correction: Enable/disable auto-correction.
  • Keyboard: Keyboard type (e.g., Number Pad, Email, URL).
  • Appearance: Keyboard style (Default, Alert).
  • Return Key: Return key label (Done, Go, Search, etc.).
  • Auto-enable Return Key: Disable return key when text is empty.
  • Secure: Hide input (e.g., for passwords).

Practical Examples

1. Restrict Input to Numbers

Allow only numeric input (and decimals):

- (BOOL)textField:(UITextField *)inputField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacement {
    NSString *allowedChars = @"0123456789.";
    NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
    NSString *filtered = [[replacement componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@""];
    if (![replacement isEqualToString:filtered]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Input Error" message:@"Only numbers and decimals are allowed." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    return YES;
}

2. Text Change Listener (Without Delegate)

Listen for text changes using addTarget:

// In viewDidLoad:
[inputField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];

- (void)textDidChange:(UITextField *)sender {
    NSLog(@"Text changed: %@", sender.text);
}

3. Keyboard Handling (Avoid Overlap)

Move the view when the keyboadr appears:

// Register for notifications:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardFrame.size.height;
    self.view.frame = CGRectMake(0, -keyboardHeight, self.view.frame.size.width, self.view.frame.size.height);
}

- (void)keyboardWillHide:(NSNotification *)notification {
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

Conclusion

UITextField offers extensive customization via properties, delegate methods, and notifications. Mastering these concepts enables robust text input handling in iOS apps. For advanced use cases, explore subclassing and custom drawing methods to create unique text field experiences.

Tags: UITextField

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.