首页 > 解决方案 > 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:

标签: iosswiftuitextviewuicollectionviewcell

解决方案


在您的 textViewDidChange 方法中,为什么将高度设置为无穷大?

self.frame.size.height +=estimatedSize.height

因此,现在您将框架的高度设置为无穷大,这就是单元格到达屏幕底部的原因。

单元格高度可以通过使用垂直或高度约束来改变构成组件的高度。假设我有 2 个 TextFields 一个放在另一个之上。然后我可以说,单元格顶部距第一个 TextField 顶部 10 点,同样,单元格底部距第二个 TextField 10 点。

现在,如果我改变任何 TextField 的高度,单元格的高度就会改变。

现在对于其他解决方案,如果您不使用自定义单元格,那么您将返回 UITableViewCell。您可以尝试在那里添加 TextField 或您想要的任何组件,然后将其返回。但请注意在使用前重新初始化单元格,因为 dequeReusableCell 将返回已使用的单元格。因此,如果该单元格已经配置了 TextField 并且您想要添加 textview,那么您可能想要使用新的。


推荐阅读