您的位置:首页 > 产品设计 > UI/UE

UITextView实现placeholder的猥琐做法

2015-08-07 16:08 399 查看
我们都知道iOS开发中的
UITextField
有个
placeholder
属性,
placeholder
可以很方便引导用户输入。但是
UITextView
却没有
placeholder
属性


猥琐法分析

如何让
UITextView
也有
placeholder
功能呢?今天给各位分享一个比较猥琐的做法。思路大概是这样的:

UITextView
text
placeholder
使用。

在开始编辑的代理方法里清除
placeholder


在结束编辑的代理方法里在设置
placeholder



实现方法


创建UITextView

UITextView *textViewPlaceholder = [[UITextView alloc] initWithFrame:CGRectMake(20, 70, SCREEN.width - 40, 100)];
textViewPlaceholder.backgroundColor = [UIColor whiteColor];
textViewPlaceholder.text = @"关注微信公众号iOS开发:iOSDevTip";
textViewPlaceholder.textColor = [UIColor grayColor];
textViewPlaceholder.delegate = self;
[self.view addSubview:textViewPlaceholder];


初始化
UITextView
,给
UITextView
text
赋值,并且给
UITextView
textColor
属性设置成灰色,让其看起来更像
placeholder


别忘了设置
UITextView
的代理,因为后面我们要用到
UITextView
的两个代理方法。


开始编辑的代理方法

- (void)textViewDidBeginEditing:(UITextView *)textView {

if ([textView.text isEqualToString:@"关注微信公众号iOS开发:iOSDevTip"]) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
}
}


在开始编辑的代理方法里面,判断如果是
UITextView
text
的值是
placeholder
,那么,就清空
text
,并且把
textColor
设置成真正的内容颜色,假设是黑色。


结束编辑的代理方法

- (void)textViewDidEndEditing:(UITextView *)textView {
if (textView.text.length<1) {
textView.text = @"关注微信公众号iOS开发:iOSDevTip";
textView.textColor = [UIColor grayColor];
}
}


在结束编辑的代理方法里,判断如果
UITextView
text
值为空,那么,就要把需要设置的
placeholder
赋值给
UITextView
text
,并且将
textColor
属性设置成灰色。


添加轻击手势

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
tapGesture.numberOfTapsRequired = 1; //点击次数
tapGesture.numberOfTouchesRequired = 1; //点击手指数
[self.view addGestureRecognizer:tapGesture];

//轻击手势触发方法
-(void)tapGesture:(UITapGestureRecognizer *)sender
{
[self.view endEditing:YES];
}


至此,就很猥琐的实现了
placeholder
功能。为了方便测试,我加了一个手势。作用是用键盘消失,这样可以测试结束编辑的时候
placeholder
会不会显示。

我看了网上一些实现
UITextView
placeholder
功能的更猥琐的做法,在
UITextView
上面盖一个
UILabel
,然后在
UITextView
的代理方法里控制
UILabel
的值。还有用两个
UITextView
实现的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: