iOS Placeholder in UITextView

UITextField擁有placeholder屬性,所以能讓input呈現灰字hint的效果,UITextView卻沒有原生的方式可以直接設定,網路上有套SAMTextView可以參考,本文提供另一種比較簡單的方式。

●h file
@interface QuestionnaireBasicViewController : UIViewController

●m file
實作UITextViewDelegate內的二個method

- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:NSLocalizedString(@"description", nil)]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor]; //optional
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@""]) {
        textView.text = NSLocalizedString(@"description", nil);
        textView.textColor = [UIColor lightGrayColor]; //optional
    }
}

實際在m file使用
// placeholder for TxtView
myTextView.delegate = self;
myTextView.text = NSLocalizedString(@"description", nil);
myTextView.textColor = [UIColor lightGrayColor]; //optional

參考資料
Placeholder in UITextView

沒有留言: