转载:http://blog.sina.com.cn/s/blog_7a1b23430102wkys.html
#import "ViewController.h"
@interface ViewController ()<</span>UITextViewDelegate>
{
UILabel *textViewPlaceholderLabel;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
1、在UITextView上加上一个UILabel
textViewPlaceholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(53, 202, 150, 25)];
textViewPlaceholderLabel.text = @"请输入你的内容";
textViewPlaceholderLabel.textColor = [UIColor grayColor];
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 200, 150, 250)];
textView.delegate = self;
textView.backgroundColor = [UIColor clearColor];
textView.layer.borderWidth = 1.0f;
textView.layer.borderColor = [UIColor blackColor].CGColor;
[self.view addSubview: textViewPlaceholderLabel];
[self.view addSubview: textView];
}
//设置textView的placeholder
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//[text isEqualToString:@""] 表示输入的是退格键
if (![text isEqualToString:@""])
{
textViewPlaceholderLabel.hidden = YES;
}
//range.location == 0 && range.length == 1 表示输入的是第一个字符
if ([text isEqualToString:@""] && range.location == 0 && range.length == 1)
{
textViewPlaceholderLabel.hidden = NO;
}
return YES;
}