實(shí)現(xiàn)方法:通過監(jiān)聽UITextView的文本變化,重繪UITextView將placeholder繪制出來。
支持xib實(shí)時(shí)預(yù)覽placeholder效果。
UITextViewWithPlaceHolder.h文件
#import <UIKit/UIKit.h>
//在定義類的前面加上IB_DESIGNABLE宏,實(shí)現(xiàn)控件在xib或storyboard上可以實(shí)時(shí)渲染
IB_DESIGNABLE
@interface UITextViewWithPlaceHolder :UITextView
//在屬性前面加上IB_DESIGNABLE宏,使該屬性在xib或storyboard上可以展示
@property(nonatomic,strong) IBInspectable NSString*placeHolder;
@property(nonatomic,strong)UIFont *placeHolderFont;
@property(nonatomic,strong)UIColor *placeHolderColor;
@end
UITextViewWithPlaceHolder.m文件
#import"UITextViewWithPlaceHolder.h"
@implementation UITextViewWithPlaceHolder
- (instancetype)initWithCoder:(NSCoder*)coder
{
self= [super initWithCoder:coder];
if(self) {
[self addNofity];
}
returnself;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self= [super initWithFrame:frame];
if(self) {
[self addNofity];
}
returnself;
}
- (void)addNofity{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange:)name:UITextViewTextDidChangeNotification object:self];
}
- (void)removeNotify{
[[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
self.textContainerInset=UIEdgeInsetsMake(10,0,0,0);//這里自定義
UIEdgeInsets insets =self.textContainerInset;
if(self.text.length==0&&self.placeHolder) {
CGRectr =CGRectMake(rect.origin.x+ insets.left+6, rect.origin.y+ insets.top, rect.size.width-insets.left-insets.right, rect.size.height-insets.top-insets.bottom);
if(self.placeHolderFont==nil) {
self.placeHolderFont=self.font;
}
if(self.placeHolderColor==nil) {
self.placeHolderColor= [UIColor lightGrayColor];
}
[self.placeHolder drawInRect:rwithAttributes:@{NSForegroundColorAttributeName:self.placeHolderColor,NSFontAttributeName:self.placeHolderFont}];
return;
}
[superdrawRect:rect];
}
- (void)textChange:(NSNotification*)notify{
[self setNeedsDisplay];
}
- (void)dealloc{
[self removeNotify];
}
@end
