Я разрабатываю приложение для чата и не могу понять, как сделать динамику высоты UICollectionViewCell
s c, в зависимости от размера текста UITextView
.
Вот что я тестировал;
class ViewController: UIViewController {
@IBOutlet var cv: UICollectionView!
let arr = ["hi hello", "func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell", "func collectionView", "// Do any additional setup after loading the view.", "extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let flowLayout = cv.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
}
// setup cv constraints here
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mm", for: indexPath) as! MessageCollectionViewCell
cell.setup(text: arr[indexPath.row])
return cell
}
}
А вот код моей ячейки:
class MessageCollectionViewCell: UICollectionViewCell {
@IBOutlet var tv: UITextView!
func setup(text: String) {
tv.text = text
tv.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tv.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0),
tv.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8),
tv.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -8),
tv.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0)
])
}
}
Это конечный результат; Скриншот
Есть идеи, что мне не хватало?