ios限制UITextField限制文本长度

 

 

#import "UITextField+LimitLength.h"

#import <objc/objc.h>

#import <objc/objc-runtime.h>

 

 

@implementation UITextField (LimitLength)

 

static NSString *kLimitTextLengthKey = @"kLimitTextLengthKey";

 

- (void)limitTextLength:(int)length

{

    objc_setAssociatedObject(self, (constvoid *)(kLimitTextLengthKey), [NSNumbernumberWithInt:length], OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    [selfaddTarget:selfaction:@selector(textFieldTextLengthLimit:) forControlEvents:UIControlEventEditingChanged];

}

 

- (void)textFieldTextLengthLimit:(id)sender

{

    NSNumber *lengthNumber = objc_getAssociatedObject(self, (constvoid *)(kLimitTextLengthKey));

    int length = [lengthNumber intValue];

    if(self.text.length > length){

        self.text = [self.text substringToIndex:length];

    }

}

 

@end

-----------------------------

用方法直接调用limitTextLength,代码如下

[_textField limitTextLength:5];

 

posted on 2014-06-05 22:58  林源  阅读(214)  评论(0编辑  收藏  举报

导航