How to set delegate of text field in Objective-C?

Viewed 27400

I'd like to customize a UITextField by limiting it to four chars. I'm trying to understand how delegates work in Objective-C and have gone through the following steps to implement this functionality, still with no luck getting a working solution.

1) Created a LimitedLengthTextField objective-c class. Made the class of type UITextField and accept objects of type < UITextFieldDelegate >.

LimitedLengthTextField.h:

@interface LimitedLengthTextField : UITextField <UITextFieldDelegate>
@end

2) Implemented the following method in LimitedLengthTextField.m:

@implementation LimitedLengthTextField

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 4) ? NO : YES;
}

@end

3) Imported "LimitedLengthTextField.h" in my CreateAccount class and tried to set the delegate of the UITextField "ssnTextField" in viewDidLoad as follows (my app accepts the last 4 digits of the user's SSN).

// Set the custom SSN textfield delegate
LimitedLengthTextField *custTextField = [[LimitedLengthTextField alloc] init];
[self.ssnTextField setDelegate:custTextField];

Based on my limited understanding of Objective-C and delegates, I've now created a class, implemented the delegate method I want, then created an instance of that class and assigned it to my UITextView object. What am I missing?

4 Answers
Related