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];