項(xiàng)目中對昵稱,用戶名會(huì)限制一些輸入個(gè)數(shù) ?于是寫了一個(gè)UITextField分類
@interface UITextField (LimitLength_h)
/**
*? 使用時(shí)只要調(diào)用此方法,加上一個(gè)長度(int),就可以實(shí)現(xiàn)了字?jǐn)?shù)限制,漢字不可以
*
*? @param length
*/
- (void)limitTextLength:(int)length;
@end
#import "UITextField+LimitLength_h.h"
#import <objc/runtime.h>
@implementation UITextField (LimitLength_h)
static NSString *kLimitTextLengthKey = @"kLimitTextLengthKey";
- (void)limitTextLength:(int)length
{
objc_setAssociatedObject(self, (__bridge const void *)(kLimitTextLengthKey), [NSNumber numberWithInt:length], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self addTarget:self action:@selector(textFieldTextLengthLimit:) forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldTextLengthLimit:(id)sender
{
NSNumber *lengthNumber = objc_getAssociatedObject(self, (__bridge const void *)(kLimitTextLengthKey));
int length = [lengthNumber intValue];
//下面是修改部分
bool isChinese;//判斷當(dāng)前輸入法是否是中文
NSArray *currentar = [UITextInputMode activeInputModes];
UITextInputMode *current = [currentar firstObject];
//[[UITextInputMode currentInputMode] primaryLanguage],廢棄的方法
if ([current.primaryLanguage isEqualToString: @"en-US"]) {
isChinese = false;
}
else
{
isChinese = true;
}
if(sender == self) {
// length是自己設(shè)置的位數(shù)
NSString *str = [[self text] stringByReplacingOccurrencesOfString:@"?" withString:@""];
if (isChinese) { //中文輸入法下
UITextRange *selectedRange = [self markedTextRange];
//獲取高亮部分
UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
// 沒有高亮選擇的字,則對已輸入的文字進(jìn)行字?jǐn)?shù)統(tǒng)計(jì)和限制
if (!position) {
if ( str.length>=length) {
NSString *strNew = [NSString stringWithString:str];
[self setText:[strNew substringToIndex:length]];
}
}
else
{
// NSLog(@"輸入的");
}
}else{
if ([str length]>=length) {
NSString *strNew = [NSString stringWithString:str];
[self setText:[strNew substringToIndex:length]];
}
}
}
}
@end