Evgeniy Kleban
Evgeniy Kleban

Reputation: 6965

Add expandable UITextView cell to UICollectionView

I have collection view when one of it's cell is cell that contain UITextView. What i want is to add textView to this cell that will expand accordingly to entered text.

I created UIView that have text view inside:

private var textView: UITextView = {
    let textView = UITextView()
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.isUserInteractionEnabled = true
    textView.isEditable = true
    return textView
  }()

Inside i set up it's constraints to superview as following:

private func setConstraints() {
  let width: CGFloat = 312
    textView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    textView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    textView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    textView.widthAnchor.constraint(equalToConstant: width).isActive = true
}

Then inside cell i set constraints like that:

func setConstraints() {
textView.topAnchor.equalTo(topAnchor).isActive = true
textView.leftAnchor.equalTo(leftAnchor).isActive = true
textView.rightAnchor.equalTo(rightAnchor).isActive = true
textView.bottomAnchor.equalTo(bottomAnchor).isActive = true
}

I did achieve behaviour when cell is expanding after textView growth, but, i didn't set bottom constraint for UITextView->UIView, that why my collection view doesn't grow (scroll) when i type large bunch of text in my cell. How to add cell with UITextView inside that will expand CollectionView it belongs to?

Upvotes: 1

Views: 156

Answers (1)

Anton Malygin
Anton Malygin

Reputation: 31

I think a better way to use manual estimation text view height and return one in

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  

This approach is more difficult than using AutoLayout but gives more control and customization possibilities.

Upvotes: 0

Related Questions