开发中总有人看这个UITextFeild的位数不顺眼,用的地方多改来改去很麻烦,于是封装了个分类来解决这个问题。
例如:证件号码限制18位,
[zjhmTextField limitLength:@"18"];
搞定!!! 实现代码如下,使用时直接copy到项目中,引入头文件即可。
.h文件中的代码
#import<UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UITextField (Luffy)
@property (nonatomic, copy) NSString *limitLen;
- (void)limitLength:(NSString*)limit;
@end
NS_ASSUME_NONNULL_END
.m文件中的代码
#import "UITextField+Luffy.h"
@implementation UITextField (Luffy)
static const char *key = "limitLen";
- (NSString *)limitLen
{
return objc_getAssociatedObject(self, key);
}
- (void)setLimitLen:(NSString*)limitLen
{
objc_setAssociatedObject(self, key, limitLen, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)limitLength:(NSString*)limit {
[self addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
self.limitLen= limit;
}
- (void)textFieldEditChanged:(UITextField*)textField {
if(textField.text.length> [self.limitLenintegerValue]) {
textField.text= [textField.textsubstringToIndex:[self.limitLenintegerValue]];
}
}