@interface PlaceHolderTextView : UITextView {
UILabel *placeHolder;//编辑区
}
@property(retain, nonatomic) NSString *placeHolderText;//显示提示文字的label
@property(retain, nonatomic) UIFont *placeHolderFont;//文字的字体
@property(assign, nonatomic) BOOL showPlaceHolderFlg;//是否显示提示文字
//手动设置placeHolder的位置
-(void) setPlaceHolderFrame: (CGRect) frame;
@end
#import "PlaceHolderTextView.h"
@implementation PlaceHolderTextView
//初始化方法
-(id) init {
self = [super init];
if(self) {
[self setPlaceHolderInit];
}
return self;
}
//初始化方法
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self setPlaceHolderInit];
}
return self;
}
//初始化placeHolder
-(void) setPlaceHolderInit {
placeHolder = [[UILabel alloc] init];
placeHolder.backgroundColor = [UIColor clearColor];
placeHolder.textColor = [UIColor grayColor];
//设置注册事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
//重写注销方法
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:self];
}
//设置字体
-(void) setPlaceHolderFont:(UIFont *)placeHolderFont {
_placeHolderFont = placeHolderFont;
placeHolder.font = _placeHolderFont;
[self setPlaceHolderFrame];
}
//设置文字
-(void) setPlaceHolderText:(NSString *)placeHolderText {
_placeHolderText = placeHolderText;
[self setPlaceHolderFrame];
}
//手动设置placeHolder的位置
-(void) setPlaceHolderFrame: (CGRect) frame {
placeHolder.frame = frame;
}
//设置placeHolder的frame
-(void) setPlaceHolderFrame {
NSString *str = @"";
UIFont *font;
if (_placeHolderText != nil) {
str = _placeHolderText;
}
if(_placeHolderFont != nil) {
font = _placeHolderFont;
} else {
font = [UIFont systemFontOfSize:12.0f];
}
placeHolder.text = str;
placeHolder.font = font;
CGSize size = [str sizeWithFont:font constrainedToSize:self.frame.size lineBreakMode:NSLineBreakByWordWrapping];
float height = size.height + 1.0;
placeHolder.frame = CGRectMake(2, 5, size.width, height >= self.frame.size.height ? self.frame.size.height : height);
// placeHolder.layer.borderWidth = 1;
}
//设置是否显示placeHolder
-(void) setShowPlaceHolderFlg:(BOOL)showPlaceHolderFlg {
if(placeHolder == nil) return;
_showPlaceHolderFlg = showPlaceHolderFlg;
if (showPlaceHolderFlg) {
[self addSubview:placeHolder];
} else {
[placeHolder removeFromSuperview];
}
}
//文字变化调用的方法
-(void) textDidChange : (NSNotification *)notification {
if (placeHolder != nil && _showPlaceHolderFlg) {//当前label没有初始化时,不做任何操作
if (self.text == nil || [self.text isEqualToString:@""]) {
[self addSubview:placeHolder];
} else {
[placeHolder removeFromSuperview];
}
}
}
@end