iOS設置textView的placeholder

轉載:http://blog.sina.com.cn/s/blog_7a1b23430102wkys.htmlhtml

 

#import "ViewController.h"spa

 

@interface ViewController ()<</span>UITextViewDelegate>htm

{blog

    UILabel *textViewPlaceholderLabel;get

}it

 

@endio

 

@implementation ViewControllerimport

 

- (void)viewDidLoad {im

    [super viewDidLoad];view

    

    一、在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;

    

}

相關文章
相關標籤/搜索