一看标题,就很屌丝!
的确,系统不给咱们,那咱们就自己弄!
具体步骤:
1,创建一个类,继承UITextView.取名ZHHTextView;
2,在drawRect:中实现placeholder,其中用到通知来监听text的change.
大概的步骤就着两步,具体实现,看代码.<一行代码解千言>
现在将.m文件代码公布如下:
#import "ZHHTextView.h"
@implementation ZHHTextView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
NSLog(@"%s",__func__);
//注册通知.要用到通知的用意:监听内容的变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewTextChange) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (void)viewTextChange {
// 执行此方法,系统自动调用drawRect:方法
[self setNeedsDisplay];
NSLog(@"%s",__func__);
}
- (void)dealloc {
//取消通知,你不取消试试,看你的项目会不会崩
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
// 如果有内容,则返回
if (self.hasText)return;
// 给placeholder添加属性
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//这里最好还是要与self.font同步
attributes[NSFontAttributeName] = [UIFont systemFontOfSize:15.0];
attributes[NSForegroundColorAttributeName] = [UIColor grayColor];
// 其实placeholder是画上去的,既然是画上去的,必须给定具体的位置与尺寸
CGFloat x = 15;
CGFloat w = rect.size.width - 2 * x;
CGFloat y = 12;
CGFloat h = rect.size.height - 2 * y;
CGRect placeholderRect = CGRectMake(x, y, w, h);
NSString* placeholder = @"请输入鸿歌的QQ...";
// 这个方法很经典
[placeholder drawInRect:placeholderRect withAttributes:attributes];
}
@end
OK了.