因为近期项目需要,需要设置占位符,网上搜了一堆都比较麻烦,后来看到国外的一大神的答案贴出了给大家学习一下。
加入代理
@interface MyClass () <UITextViewDelegate>
@end创建
UITextView *myUITextView = [[UITextView alloc] init];
myUITextView.delegate = self;
myUITextView.text = @"placeholder text here...";
myUITextView.textColor = [UIColor lightGrayColor]; //optional
实现代理方法
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@"placeholder text here..."]) {
textView.text = @"";
textView.textColor = [UIColor blackColor]; //optional
}
[textView becomeFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@""]) {
textView.text = @"placeholder text here...";
textView.textColor = [UIColor lightGrayColor]; //optional
}
[textView resignFirstResponder];
}OK 就是这么简单
本文介绍了一种简单的方法来为UITextView设置占位符文本。通过实现UITextViewDelegate方法,在编辑开始和结束时更改文本颜色及内容,实现类似placeholder的效果。

7121

被折叠的 条评论
为什么被折叠?



