码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-04 16:49:37      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

   //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

  

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

标签:

原文地址:http://www.cnblogs.com/binglin92/p/4201382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!