首页 > 代码库 > UITextField限制文字的长度 支持中文联想

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 = http://www.mamicode.com/objc_getAssociatedObject(self, @selector(textLengthRange));>

  

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