原文地址: http://blog.csdn.net/l_nna
UITextView官方没有给提供提示信息属性自己搞一个
- .h文件
#import <UIKit/UIKit.h>
@interface NNATextView : UITextView
@property (nonatomic, strong) NSString *placeHolder;
@property (nonatomic, strong) UIColor *placeHolderColor;//提示消息颜色
@end
- .m文件
#import "NNATextView.h"
@interface NNATextView ()
@property (nonatomic, strong) UIColor *superTextColor;//输入框文本颜色
@end
@implementation NNATextView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self awakeFromNib];
}
return self;
}
- (void)awakeFromNib {
[self addObserver];
}
#pragma mark - 添加通知
- (void)addObserver {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:self];
}
#pragma mark - 移除通知
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)textDidBeginEditing:(NSNotification *)notification {
if ([super.text isEqualToString:_placeHolder]) {
super.text = @"";
[super setTextColor:_superTextColor];
}
}
- (void)textDidEndEditing:(NSNotification *)notification {
if (super.text.length == 0) {
super.text = _placeHolder;
[super setTextColor:_placeHolderColor];
}
}
#pragma mark - Getter
- (NSString *)text {
NSString *textStr = [super text];
if ([textStr isEqualToString:_placeHolder]) {
return @"";
}
return textStr;
}
#pragma mark - Setter
- (void)setTextColor:(UIColor *)textColor {
[super setTextColor:textColor];
_superTextColor = textColor;
}
- (void)setPlaceHolder:(NSString *)placeHolder {
_placeHolder = placeHolder;
[self textDidEndEditing:nil];
}
@end