标签:
//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
标签:
原文地址:http://www.cnblogs.com/binglin92/p/4201382.html