UITextField限制文字的长度 支持中文联想

   //UITextField+text_constraints.h



@interface UITextField (text_constraints) //考虑到有的地方的文本长度是一个范围eg:2-10,所以使用NSRange @property (nonatomic, assign) NSRange textLengthRange; - (BOOL)shouldChangeInRange:(NSRange)range replaceString:(NSString *)string; @end

  

//  UITextField+text_constraints.m

#import "UITextField+text_constraints.h"
#import <objc/runtime.h>

@implementation UITextField (text_constraints)

#pragma mark - textLengthRange
/**
 *  添加文本变化的通知,输入拼音选择汉字时会有通知
 *  delegate shouldChangeCharactersInRange方法选择汉字时不会调用
 */
- (void)addTextChangeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeNotif:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)textFieldTextDidChangeNotif:(NSNotification *)notif{
    UITextField *textField = notif.object;
    NSUInteger  maxNumber  = self.textLengthRange.location + self.textLengthRange.length;
    if (textField.markedTextRange == nil) {
        if (textField.text.length > maxNumber) {
            textField.text = [textField.text substringToIndex:maxNumber];
        }
    }
}

- (void)setTextLengthRange:(NSRange)textLengthRange{
    [self addTextChangeNotification];
    objc_setAssociatedObject(self, @selector(textLengthRange), [NSValue valueWithRange:textLengthRange], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSRange)textLengthRange{
    NSValue *value = objc_getAssociatedObject(self, @selector(textLengthRange));
    if (value) {
        return value.rangeValue;
    }
    return NSMakeRange(0, NSUIntegerMax);
}


#pragma mark - textField replace
//供(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;使用
- (BOOL)shouldChangeInRange:(NSRange)range replaceString:(NSString *)string{
    if (range.location >= (self.textLengthRange.location + self.textLengthRange.length)
        && (self.markedTextRange == nil && range.length == 0)){
        return NO;
    }
    return YES;
}

@end

  现已整理一个UITextView和UITextField字数限制的开源库 支持pod

     https://github.com/Binglin/UITextRange

posted on 2015-01-04 16:09  永远的冰蝴蝶  阅读(823)  评论(0)    收藏  举报

导航