Set the maximum character length of a UITextField

前端 未结 30 1707
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  青春惊慌失措
    2020-11-22 03:06

    I have implemented a UITextField Extension to add a maxLength property to it.

    It's based on Xcode 6 IBInspectables, so you can set the maxLength limit on the Interface builder.

    Here is the implementation:

    UITextField+MaxLength.h

    #import 
    
    @interface UITextField_MaxLength : UITextField
    
    @property (nonatomic)IBInspectable int textMaxLength;
    @end
    

    UITextField+MaxLength.m

    #import "UITextField+MaxLength.h"
    
    @interface UITextField_MaxLength()
    
    @property (nonatomic, assign) id  superDelegate;
    
    @end
    
    @implementation UITextField_MaxLength
    
    - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
        //validate the length, only if it's set to a non zero value
        if (self.textMaxLength>0) {
            if(range.length + range.location > textField.text.length)
                return NO;
    
            if (textField.text.length+string.length - range.length>self.textMaxLength) {
                return NO;
            }
        }
    
        //if length validation was passed, query the super class to see if the delegate method is implemented there
        if (self.superDelegate && [self.superDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
            return [self.superDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
        }
        else{
            //if the super class does not implement the delegate method, simply return YES as the length validation was passed
            return YES;
        }
    }
    
    - (void)setDelegate:(id)delegate {
        if (delegate == self)
            return;
        self.superDelegate = delegate;
        [super setDelegate:self];
    }
    
    //forward all non overriden delegate methods
    - (id)forwardingTargetForSelector:(SEL)aSelector {
        if ([self.superDelegate  respondsToSelector:aSelector])
            return self.superDelegate;
    
        return [super forwardingTargetForSelector:aSelector];
    }
    
    - (BOOL)respondsToSelector:(SEL)aSelector {
        if ([self.superDelegate respondsToSelector:aSelector])
            return YES;
    
        return [super respondsToSelector:aSelector];
    }
    @end
    

提交回复
热议问题