UITextField限制文字输入字数
在我们平常的开发过程中,经常会遇到需要限制UITextField字数输入的个数,使用UITextField的- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string代理方法限制字数长度需要分开英文跟中文的长度,为了方便使用,可以用Category方式去定义限制UITextField字数输入的方法,当输入的字数达到最大个数,输入框再无法输入内容,使用起来很方便,直接用textField.qx_maxLength = xx,就可以限制文字输入个数。
一下代码可以直接复制粘贴使用:
@interface UITextField (QXInputLimit)
@property (assign, nonatomic) NSInteger qx_maxLength;//if <=0, no limit
@end
#import "UITextField+QXInputLimit.h"
static const void *QXTextFieldInputLimitMaxLength = &QXTextFieldInputLimitMaxLength;
@implementation UITextField (QXInputLimit)
- (NSInteger)qx_maxLength {
return [objc_getAssociatedObject(self, QXTextFieldInputLimitMaxLength) integerValue];
}
- (void)setQx_maxLength:(NSInteger)maxLength {
objc_setAssociatedObject(self, QXTextFieldInputLimitMaxLength, @(maxLength), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self addTarget:self action:@selector(qx_textFieldTextDidChange) forControlEvents:UIControlEventEditingChanged];
}
- (void)qx_textFieldTextDidChange {
NSString *toBeString = self.text;
//获取高亮部分
UITextRange *selectedRange = [self markedTextRange];
UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
//没有高亮选择的字,则对已输入的文字进行字数统计和限制
//在iOS7下,position对象总是不为nil
if ( (!position ||!selectedRange) && (self.qx_maxLength > 0 && toBeString.length > self.qx_maxLength))
{
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:self.qx_maxLength];
if (rangeIndex.length == 1)
{
self.text = [toBeString substringToIndex:self.qx_maxLength];
}
else
{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.qx_maxLength)];
NSInteger tmpLength;
if (rangeRange.length > self.qx_maxLength) {
tmpLength = rangeRange.length - rangeIndex.length;
}else{
tmpLength = rangeRange.length;
}
self.text = [toBeString substringWithRange:NSMakeRange(0, tmpLength)];
}
}
}