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

来源:互联网 发布:c语言socket网络编程 编辑:程序博客网 时间:2024/05/13 03:10

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

.h文件

 


#import <UIKit/UIKit.h>


@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:[UIColorgrayColor];


    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(textDidBegin)name:UITextViewTextDidBeginEditingNotificationobject:self];


    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(textDidEnd)name:UITextViewTextDidEndEditingNotificationobject:self];

    

    

 

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

}


-(void)textDidBegin{

    

    if ([self.textisEqualToString:placheolder]) {

        self.text =@"";

        self.textColor = [UIColorblackColor];

        

        

    }

    

    

    

    

}

-(void)textDidEnd{

    

    if([self.textisEqualToString:@""]){

        

        self.text =placheolder;

        self.textColor =_placeholderColor?_placeholderColor:[UIColorgrayColor];


    }

    

}



0 0
原创粉丝点击