John Lane
John Lane

Reputation: 1132

Subclass of UITextField

I want to subclass UITextField and have a method that sets the maximum number of characters. allowed. In the init method of this subclass I try setting the inputDelegate to self but the callbacks aren't triggered. Also this is an iOS 5 thing only. My question is what protocol or notification would allow me to fire an event when a key is tapped so that I don't have to implement the UITextField delegate in my view controller to achieve this limit.

Thanks.

Upvotes: 1

Views: 2274

Answers (1)

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

You could do it like this, create a delegate class for you textfield

.m file

@implementation LimitedTextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField.text.length >= 5 && ![string isEqualToString:@""])
        return NO;

    return YES;
}
@end

.h file

@interface LimitedTextFieldDelegate : UITextField<UITextFieldDelegate>
@end

in the UITextField subclass do the following

- (id)init
{
    self = [super init];
    if (self) {
        //limitedDelegate is a property of your textfield subclass
        self.limitedDelegate = [[LimitedTextFieldDelegate alloc] init];
        self.delegate = self.limitedDelegate;
    }
    return self;


}

Upvotes: 1

Related Questions