天天看點

UITextView如何設定提示性文字

給UITextView設定提示性文字,輸入時提示性文字消失。結束輸入時,若輸入内容為空,則提示性文字再次出現。

例如:提示性文字為“随便說點什麼吧”;

#define TextViewDefaultText @"随便說點什麼吧"
self.textView.text = TextViewDefaultText;
self.textView.textColor = [UIColor lightGrayColor];
           

在UITextViewDelegate方法中實作:

#pragma mark --------TextViewDelegate------
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:TextViewDefaultText]) {
        textView.text = @"";
    }
    textView.textColor = [UIColor blackColor];
    return YES;
}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    NSString *str = [textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([str isEqualToString:@""]) {
        textView.text = TextViewDefaultText;
        textView.textColor = [UIColor lightGrayColor];
    }
    return YES;
}
           

這樣就OK了!