美文网首页iOS高质量博客iOS学习笔记iOS Developer
UITextView的分类(添加占位文字和最大输入个数)

UITextView的分类(添加占位文字和最大输入个数)

作者: 逍遥晨旭 | 来源:发表于2017-04-23 06:04 被阅读400次

思路:

1、通过runtime添加两个字符串属性,供外接访问。一个为设置占位字符串(placeholder)使用,一个为设置最大文字个数(limitLength)使用。
2、通过runtime将UITextView和两个UILabel关联起来,一个用做显示占位字符串(placeholderLabel)使用,一个用做显示最大文字个数(wordCountLabel)使用。
3、在占位字符串(placeholder)和最大文字个数(limitLength)的set方法中分别调用第二步中两个UILabel的初始化方法。
4、注册两个通知(通知的名字都叫:UITextViewTextDidChangeNotification,但监听方法不一样):一个用作监听UITextView输入字数,有则不显示占位文字,没有就显示占位文字。另一个用作监听是否超过最大输入字数使用,没有超过可继续使用,超过则截取到最大字数,后面的不显示,也无法输入。(倘若提示用户超出最大字数,可以在通知的监听方法中判断提示)

效果图如下:

效果图
此分类使用的时候,只是在正常创建UITextView时多了两个属性设置:
self.addessalDetailTextView.placeholder = @"请填写详细地址,不少于120个字";
self.addessalDetailTextView.limitLength = @120;

具体使用代码如下(是不是代码很少):

UITextView *textView = [[UITextView alloc] init];
textView.frame = CGRectMake(10, 10, 300, 150);
textView.center = self.view.center;
textView.placeholder = @"请填写详细地址,不多于120个字";
textView.limitLength = @120;
[self.view addSubview:textView];

也可以使用xib关联,简单方便。

下面就看分类(UITextView+CLTextView)的具体实现:

1、UITextView+CLTextView.h的实现,这也就是思路中的第一步

@property (nonatomic,strong) NSString *placeholder;//占位符
@property (copy, nonatomic) NSNumber *limitLength;//字数限制

2、UITextView+CLTextView.m的实现

引入#import <objc/runtime.h>头文件

@interface UITextView ()
@property (nonatomic,strong) UILabel *placeholderLabel;//占位符
@property (nonatomic,strong) UILabel *wordCountLabel;//计算字数
@end
@implementation UITextView (YLTextView)

static NSString *PLACEHOLDLABEL = @"placelabel";
static NSString *PLACEHOLD = @"placehold";
static NSString *WORDCOUNTLABEL = @"wordcount";
static const void *limitLengthKey = &limitLengthKey;


#pragma mark -- setter/getter方法

//显示占位符label的setter/getter方法
-(void)setPlaceholderLabel:(UILabel *)placeholderLabel {
    objc_setAssociatedObject(self, &PLACEHOLDLABEL, placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UILabel *)placeholderLabel {
    return objc_getAssociatedObject(self, &PLACEHOLDLABEL);
}

//显示字数label的setter/getter方法
- (void)setWordCountLabel:(UILabel *)wordCountLabel {
    objc_setAssociatedObject(self, &WORDCOUNTLABEL, wordCountLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UILabel *)wordCountLabel {
    return objc_getAssociatedObject(self, &WORDCOUNTLABEL);
}

//供外接访问的占位字符串,以便设置占位文字的setter/getter方法
- (void)setPlaceholder:(NSString *)placeholder {
    objc_setAssociatedObject(self, &PLACEHOLD, placeholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setPlaceHolderLabel:placeholder];
}

- (NSString *)placeholder {
    return objc_getAssociatedObject(self, &PLACEHOLD);
}

//供外接访问的最大输入字数,设置最大文字个数的setter/getter方法
- (NSNumber *)limitLength {
    return objc_getAssociatedObject(self, limitLengthKey);
}

- (void)setLimitLength:(NSNumber *)limitLength {
    objc_setAssociatedObject(self, limitLengthKey, limitLength, OBJC_ASSOCIATION_COPY_NONATOMIC);

    [self addLimitLengthObserver:[limitLength intValue]];
    [self setWordcountLable:limitLength];
}

#pragma mark -- 配置占位符标签
- (void)setPlaceHolderLabel:(NSString *)placeholder {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextViewTextDidChangeNotification object:self];
    // 占位字符
     
    self.placeholderLabel = [[UILabel alloc] init];
    self.placeholderLabel.font = [UIFont systemFontOfSize:13.];
    self.placeholderLabel.text = placeholder;
    self.placeholderLabel.numberOfLines = 0;
    self.placeholderLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.placeholderLabel.textColor = [UIColor lightGrayColor];
    CGRect rect = [placeholder boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.frame)-7, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13.]} context:nil];
    self.placeholderLabel.frame = CGRectMake(7, 7, rect.size.width, rect.size.height);
    [self addSubview:self.placeholderLabel];
    self.placeholderLabel.hidden = self.text.length > 0 ? YES : NO;
}

#pragma mark -- 设置字数限制标签
- (void)setWordcountLable:(NSNumber *)limitLength {
    //字数限制
    self.wordCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.frame) - 65, CGRectGetHeight(self.frame) - 20, 60, 20)];
    self.wordCountLabel.textAlignment = NSTextAlignmentRight;
    self.wordCountLabel.textColor = [UIColor lightGrayColor];
    self.wordCountLabel.font = [UIFont systemFontOfSize:13.];
    if (self.text.length > [limitLength integerValue]) {
        self.text = [self.text substringToIndex:[self.limitLength intValue]];
    }
    self.wordCountLabel.text = [NSString stringWithFormat:@"%lu/%@",(unsigned long)self.text.length,limitLength];
    [self addSubview:self.wordCountLabel];
}

#pragma mark -- 注册限制位数的通知
- (void)addLimitLengthObserver:(int)length {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitLengthEvent) name:UITextViewTextDidChangeNotification object:self];
}

#pragma mark -- 限制输入的位数
- (void)limitLengthEvent {

    if ([self.text length] > [self.limitLength intValue]) {

        self.text = [self.text substringToIndex:[self.limitLength intValue]];
    }
}

#pragma mark -- NSNotification
- (void)textFieldChanged:(NSNotification *)notification {
    if (self.placeholder) {
        self.placeholderLabel.hidden = YES;
        
        if (self.text.length == 0) {
            
            self.placeholderLabel.hidden = NO;
        }
    }
    if (self.limitLength) {
        
        NSInteger wordCount = self.text.length;
        if (wordCount > [self.limitLength integerValue]) {
            wordCount = [self.limitLength integerValue];
 #pragma mark -- 想提示用户输入已经超出最大字数可以打开此行代码
//            UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"超过最大字数" message:@"您已经超出了最大字数,超出部分将无法显示" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//            [view show];
        }
        self.wordCountLabel.text = [NSString stringWithFormat:@"%ld/%@",wordCount,self.limitLength];
    }
}

总结:

关键点是:runtime的使用和通知的监听。然后就没什么了。

相关文章

网友评论

  • iDog:用的时候发现 placeholder的位置和光标位置有点尬
    [self setValue:self.placeholderLabel forKey:@"_placeholderLabel"];
    然后加了这行代码 不尬了
    placeholderLabel的左边 y 写死不好看
    逍遥晨旭:@iDog 谢谢,很好的建议
  • iDog:奈何没demo啊 不然直接copy 岂不快哉
    iDog:@此生逍遥 已经copy好了:smile:
    逍遥晨旭:@iDog 创建文件拷进去就over了

本文标题:UITextView的分类(添加占位文字和最大输入个数)

本文链接:https://www.haomeiwen.com/subject/yyitzttx.html