我在 SO 上看到了很多与此相关的问题,但是,没有一个与我的问题有关。
我要创建一个具有消息传递功能的应用程序。类似于 Apple 在他们的应用程序中有 Mail 和 LinkedIn 在他们的应用程序中有邮件功能,我想要一个包含 3 行的 UITableView
。第三行有 UITextView
,它必须随着用户输入而增长。我的代码如下:
- (void)textViewDidChange:(UITextView *)textView {
if (bodyText.contentSize.height > currentContentHeight) {
currentContentHeight = bodyText.contentSize.height;
[tblView beginUpdates];
[tblView endUpdates];
[bodyText setFrame:CGRectMake(0, 0, 310.0, currentContentHeight)];
bodyText.selectedRange = NSMakeRange(textView.text.length - 1, 0);
} else {
currentContentHeight = minimumContentHeight;
[tblView beginUpdates];
[tblView endUpdates];
}
}
当我在 iPhone 上按下回车键时,它会停机并完美运行。问题是,如果我转到中心或 UITextView
的任何其他中间部分,它似乎会产生有趣的行为,因为它错误地获取了 contentSize
。例如:
- 我按回车键 10 次
- 转到第五行并输入“dog”
- 它根据第 5 行获取
contentHeight
,是否有意义?
有没有办法根据当前的所有文本来计算呢?如果上面遗漏了什么,请告诉我。我广泛阅读了以下内容:
http://dennisreimann.de/blog/uitextview-height-in-uitableviewcell/
https://stackoverflow.com/questions/985394/growing-uitextview-and-uitableviewcell
最佳答案
我用以下代码编辑了上面的代码,它对我有用:
- (void)textViewDidChange:(UITextView *)textView {
// Get the number of lines in the current view
NSUInteger lines = textView.text.length;
if ((lines * 25) > currentContentHeight && (lines * 25) >= minimumContentHeight && bodyText.contentSize.height > minimumContentHeight) {
currentContentHeight = bodyText.contentSize.height;
} else if (lines < 5){
currentContentHeight = minimumContentHeight;
}
[tblView beginUpdates];
[tblView endUpdates];
[bodyText setFrame:CGRectMake(5, 5, 310, currentContentHeight)];
bodyText.selectedRange = [bodyText selectedRange];
}
我一开始根据手机大小设置了currentContentHeight
等于minimumContentHeight
。
关于ios - UITextView 在 UITableViewCell 内部增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404634/