[IOS]——利用drawRect方法绘画UITextView的占位字

由于UITextView没有占位字的属性,但如果想要做到像UITextField那样能够显示占位字,那么我们就需要自定义一个类继承于UITextView,在新创建的类上添加占位字属性
效果图

%title插图%num
方法介绍
新建一个类继承于UITextView,在新建类的.h文件创建占位字属性(.h文件创建的原因在于要被其他类调用,如果在.m文件里设置那这个属性只是这个类私有的)

%title插图%num

在这个新建类的.m文件里完善它的方法
#import “placeholderview.h”

@implementation placeholderview
//这个方法是对象初始化时都会调用的
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self){
//文本内容改变时监听通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textchange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)textchange
{
//重新绘制
[self setNeedsDisplay];
}
//如果要完善自定义控件,就是你在外面改属性时就会显示出相应的东西,所以就要做到重写set方法
-(void)setPlaceColor:(UIColor *)placeColor
{
_placeColor = [placeColor copy];
//重新绘画一次
[self setNeedsDisplay];
}
-(void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
//重新绘画一次
//setNeedsDisplay这个方法不是一设置就会调用,它是收集好全部信息再重新画一次
//setNeedsDisplay这个方法是会自动去调用drawRect这个方法的
[self setNeedsDisplay];
}
//这个方法每次执行会先把之前绘制的去掉
-(void)drawRect:(CGRect)rect
{
if(!self.hasText){
//文字的属性
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSFontAttributeName] = self.font;
dict[NSForegroundColorAttributeName] = self.placeColor;
//画文字(rect是textView的bounds)
NSLog(@”%f”,rect.size.width);
CGRect textRect = CGRectMake(5, 8, rect.size.width, rect.size.height);
[self.placeholder drawInRect:textRect withAttributes:dict];
}
}