一、设置PlaceHolder
1.声明属性和代理
<UITextViewDelegate>
@property(nonatomic,strong)UILabel *PLlab;
@property(nonatomic,strong)UITextView *inputView;
2.创建textview和lable
//输入框视图
inputView = [[UITextView alloc]initWithFrame:CGRectMake(5, 72, WIDTH-10, (HEIGHT-70)/3-20)];
inputView.keyboardType = UIKeyboardTypeDefault;
inputView.font = [UIFont systemFontOfSize:14];
inputView.delegate = self;
inputView.textColor = TEXTCOLOR;
[self.view addSubview:inputView];
// [self.inputView setValue:[UIColor colorWithHex:0xbababa] forKeyPath:@"_placeholderLabel.textColor"];
// [self.inputView setValue:TEXTFONT(16) forKeyPath:@"_placeholderLabel.font"];
self.PLlab = [[UILabel alloc]initWithFrame:CGRectMake(12, 0, WIDTH, 40)];
self.PLlab.text = @"您此刻的想法,最多1500字";
self.PLlab.font = [UIFont systemFontOfSize:14];
self.PLlab.textColor = TEXTTINTCOLOR;
[inputView addSubview:self.PLlab];
3.开始编辑时调用相应方法隐藏lable
- (void)textViewDidBeginEditing:(UITextView *)textView{
self.PLlab.hidden = YES;
}
4.点击view缩回键盘时显示lable
- (void)touchesBegan:(NSSet<UITouch> *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
if (inputView.text.length > 0) {
self.PLlab.hidden = YES;
}else{
self.PLlab.hidden = NO;
}
}
二、注意点
1.在输入框的textViewDidChange代理方法里面,如果直接调用textView.text或者textView.attributedText会导致苹果简体键盘输入不了英文;需要调用UITextRange和UITextPosition,在赋值attributedText才能解决;
2.输入框允许输入emoji后,并且调用了subStringToIndex方法,会导致表情被截断,出现一个带框的A的异常符号,提交网络请求会崩溃;解决方案有两种:一种是把带emoji的文字进行转码;一种是遍历文字中的字符,将表情算作一个字符长度;
3.textFiled是一个道理;