首页 > 解决方案 > Swift - 具有动态高度的 UICollectionViewCells

问题描述

我正在开发一个聊天应用程序,但我不知道如何使UICollectionViewCells 的高度动态化,具体取决于UITextViews 的文本有多大。

这是我一直在测试的;

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)
        ])
    }
}

这就是最终结果; 截屏

知道我错过了什么吗?

标签: swiftautolayoutuicollectionviewcell

解决方案


我终于修好了!我应该做的就是为单元格本身添加一个宽度约束,这样它就不会在水平方向上变得更大!

NSLayoutConstraint.activate([
   self.contentView.widthAnchor.constraint(equalToConstant: maxDeviceWidth)
])

推荐阅读