ios - I have a UICollectionViewCell with multiple UITextViews. When any of the textViews increase in height, I want the UICollectionViewCell to do the same
问题描述
I have (3) UITextViews
, (1) UITextField
and (1) UILabel
within a single UICollectionViewCell
. I have all the textViews changing in height when the text wraps onto a second line with a textViewDidChange
function in an extension that conforms to the UITextViewDelegate
protocol:
func textViewDidChange(_ textView: UITextView) {
let size = CGSize(width: frame.width, height: .infinity)
let estimatedSize = textView.sizeThatFits(size)
textView.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
}
Ideally, whenever any of the textViews in my cell increase in height, I'd like that to increase the height of the cell.
I tried putting:
self.frame.size.height += estimatedSize.height
in the if constraint.firstAttribute == .height
section, but that only increased the height of the cell until it reaches the bottom of the screen. And I'd like the user to be able to enter as much text as they'd like.
Is there a loop I should be using to edit the height of the cell whenever this textViewDidChange changes the height of a textView?
I'm super stumped, so any help would be awesome! Thanks in advance!
CAVEAT:
- After alot of searching, I found a bunch of answers that show how to dynamically increase the height of a cell. However, I don't know how to make unique cells within a
UICollectionView
. If the most elegant solution here is to put all the textViews, the textField, and the label into unique cells, please show me how to do that!
解决方案
在您的 textViewDidChange 方法中,为什么将高度设置为无穷大?
self.frame.size.height +=estimatedSize.height
因此,现在您将框架的高度设置为无穷大,这就是单元格到达屏幕底部的原因。
单元格高度可以通过使用垂直或高度约束来改变构成组件的高度。假设我有 2 个 TextFields 一个放在另一个之上。然后我可以说,单元格顶部距第一个 TextField 顶部 10 点,同样,单元格底部距第二个 TextField 10 点。
现在,如果我改变任何 TextField 的高度,单元格的高度就会改变。
现在对于其他解决方案,如果您不使用自定义单元格,那么您将返回 UITableViewCell。您可以尝试在那里添加 TextField 或您想要的任何组件,然后将其返回。但请注意在使用前重新初始化单元格,因为 dequeReusableCell 将返回已使用的单元格。因此,如果该单元格已经配置了 TextField 并且您想要添加 textview,那么您可能想要使用新的。
推荐阅读
- php - 我想在 laravel 的选择选项菜单中显示整个国家列表
- linux - logrotate:即使我使用了 -f 选项,每日轮换也不起作用
- javascript - Travis CI 的授权回调 URL 是什么。生成 Github 令牌
- python-3.x - python chatclean 和电子邮件清理
- android - Android NDK:找不到平台文件(头文件和库)
- c++11 - 为什么 make_unique 不适用于具有内联构造函数的类?
- mysql - Nginx Docker 卷为空
- wordpress - WordPress 迁移计划
- python - Pandas DataFrame groupby 列到 dict
- wordpress - 在 wordpress 帖子中插入图像以调整大小的最佳方法