您的位置:首页 > 移动开发 > IOS开发

iOS开发使用textView代替textField时,textView的placeholder问题

2015-05-26 16:58 218 查看
iOS开发很多时候我们需要使用textView代替textField,因为textfield不能自动换行,那么textView就面临着placeholder提示文字的问题,其实实现原理就是在textView下面再添加一个用UITextView创建的_placeholderLabel,通过控制这个_placeholderLabel的隐藏与显示来实现UItextField的placeholder的效果。

本文还会讲到在输入的过程中textView如何动态适应内容的高度。以及还会提及到如何获取textView的行数问题。

//创建段落样式
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;// 字体的行间距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:15],
NSParagraphStyleAttributeName:paragraphStyle
};

//这个_placeholderLabel是贴在_textView下面的,
_placeholderLabel = [[UITextView alloc] initWithFrame:CGRectMake(20, 64, kScreenWidth-40, 100)];
_placeholderLabel.attributedText = [[NSAttributedString alloc] initWithString:@"输入你的内容" attributes:attributes];
[_placeholderLabel setEditable:NO];
[self.view addSubview:_placeholderLabel];

UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 64, kScreenWidth-40, 100)];
_textView.delegate = self;
_textView.backgroundColor = [UIColor clearColor];//这个_textView的背景颜色必须是透明的,才能保证看到它下面的_placeholderLabel中的提示文字
_textView.layer.borderColor = [UIColor redColor].CGColor;
_textView.layer.borderWidth = 0.5f;
[self.view addSubview:_textView];
_textView.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];

//实现UITextView的协议方法
#pragma mark - UITextViewDelegate
-(void)textViewDidChange:(UITextView *)textView

{
// textview 改变字体的行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];//段落样式
paragraphStyle.lineSpacing = 5;// 字体的行间距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:15],
NSParagraphStyleAttributeName:paragraphStyle
};

textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];

//获取textView的行数
//    float rows = (textView.contentSize.height - textView.textContainerInset.top - textView.textContainerInset.bottom) / textView.font.lineHeight;

//textview的高度和输入的所有内容的高度保持一致(这个看需求)
//    [textView setHeight:textView.contentSize.height];

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{
if (![text isEqualToString:@""]/*当不是输入退格键时*/)
{
_placeholderLabel.hidden = YES;
}

if ([text isEqualToString:@""] && range.location == 0 && range.length == 1/*输入的第一个字符是退格键*/)
{
_placeholderLabel.hidden = NO;
}

return YES;

}


本文参考自这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐