1.// 创建textView
UITextView*textView =[[UITextViewalloc]initWithFrame:CGRectMake(20,70,SCREEN.width-40,100)];
textView.backgroundColor= [UIColorwhiteColor];
textView.text =@"我是placeholder";
textView.textColor = [UIColorgrayColor];
textView.delegate =self;
[self.view addSubview:textView];
#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView*)textView{
if(textView.text.length <1){
textView.text =@"我是placeholder";
textView.textColor = [UIColorgrayColor];
}
}
- (void)textViewDidBeginEditing:(UITextView*)textView{
if([textView.text isEqualToString:@"我是placeholder"]){
textView.text=@"";
textView.textColor=[UIColorblackColor];
}
}
2.
#import <UIKit/UIKit.h>
@interfaceWSPlaceholderTextView:UITextView
/** 占位文字 */@property(nonatomic,copy)NSString*placeholder;
/*占位文字颜色*/@property(nonatomic,strong)UIColor*placeholderColor;
@end
#import"WSPlaceholderTextView.h"
@implementationWSPlaceholderTextView
- (instancetype)initWithFrame:(CGRect)frame{
if(self= [superinitWithFrame:frame]) {
// 设置默认字体self.font = [UIFontsystemFontOfSize:15];
// 设置默认颜色self.placeholderColor = [UIColorgrayColor];
// 使用通知监听文字改变[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(textDidChange:) name:UITextViewTextDidChangeNotificationobject:self];
}
return self;
}
- (void)textDidChange:(NSNotification*)note{
// 会重新调用drawRect:方法[selfsetNeedsDisplay];}
- (void)dealloc{ [[NSNotificationCenterdefaultCenter] removeObserver:self];}
/**
* 每次调用drawRect:方法,都会将以前画的东西清除掉
*/
- (void)drawRect:(CGRect)rect{
// 如果有文字,就直接返回,不需要画占位文字
if(self.hasText)return;
// 属性NSMutableDictionary*attrs = [NSMutableDictionarydictionary];
attrs[NSFontAttributeName] =self.font;
attrs[NSForegroundColorAttributeName] =self.placeholderColor;
// 画文字rect.origin.x =5;
rect.origin.y =8;
rect.size.width -=2* rect.origin.x;
[self.placeholder drawInRect:rect withAttributes:attrs];}
- (void)layoutSubviews{
[superlayoutSubviews];
[selfsetNeedsDisplay];}
#pragma mark - setter
- (void)setPlaceholder:(NSString*)placeholder{
_placeholder = [placeholdercopy];
[selfsetNeedsDisplay];}
- (void)setPlaceholderColor:(UIColor*)placeholderColor{
_placeholderColor = placeholderColor;
[selfsetNeedsDisplay];}
- (void)setFont:(UIFont*)font{
[supersetFont:font];
[selfsetNeedsDisplay];}
- (void)setText:(NSString*)text{
[supersetText:text];
[selfsetNeedsDisplay];}
- (void)setAttributedText:(NSAttributedString*)attributedText{
[supersetAttributedText:attributedText];
[selfsetNeedsDisplay];}
@end
http://www.jianshu.com/p/9edb8be75e0b