美文网首页
给UITextView添加Placeholder最简单易懂的方法

给UITextView添加Placeholder最简单易懂的方法

作者: A橙汁不加橙 | 来源:发表于2018-08-14 09:12 被阅读0次

今天项目里又需要写一个有占位符的UITextView控件,以前的话都是用代理来判断实现的,每个类里都需要判断,太麻烦了,所以为了便于以后再次用到需要占位符的UITextView,决定自己写一个自定义的UITextView,首先我想到的就是继承。网上也有很多利用分类Categories的方法,利用runtime和新增的UILabel控件来做这个占位符效果实在有点大智若愚。故自己写了一个,代码很简单,

.h文件

#import 

@interface WLTUITextView : UITextView

-(void)setPlaceholder:(NSString *)str and:(UIColor *)color;

@end

.m文件

#import "WLTUITextView.h"

@implementation WLTUITextView{

 NSString * placheolder;

 UIColor * _placeholderColor;

}

-(void)setPlaceholder:(NSString *)str and:(UIColor *)color{

 _placeholderColor = color;

 placheolder = str;

 self.text = str;

 self.textColor = _placeholderColor?_placeholderColor:[UIColor grayColor];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidBegin) name:UITextViewTextDidBeginEditingNotification object:self];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEnd) name:UITextViewTextDidEndEditingNotification object:self];

 //这里使用KVO时,会出现死循环,因为占位符的逻辑问题。所以这里不适合用KVO 故采用以上的方法更简单。网上的那些使用runtime机制又加了label来做占位符的方法实在是有点大智若愚的感觉。我觉得用最简单的代码解决复杂问题的能力就是一个人的逻辑思维能力。

}

-(void)textDidBegin{

 if ([self.text isEqualToString:placheolder]) {

 self.text = @"";

 self.textColor = [UIColor blackColor];

    }

}

-(void)textDidEnd{

 if([self.text isEqualToString:@""]){

 self.text = placheolder;

 self.textColor = _placeholderColor?_placeholderColor:[UIColor grayColor];

    }

}

相关文章

网友评论

      本文标题:给UITextView添加Placeholder最简单易懂的方法

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