UICollectionView:如何根据高度实现UICollectionViewCell的自动调整大小?

时间:2017-11-15 18:32:42

标签: ios swift collectionview autoresize

目前,我手动计算每个单元格的高度,具体取决于标签和图像的高度。我有一个方形图像,其长度等于屏幕的宽度。但我正在寻找其他替代方案,我不必手动这样做。我想要像tableview这样的东西,它是根据约束自动计算的。

1 个答案:

答案 0 :(得分:0)

这里有一个可以帮助你的小设置。

Apple为UICollectionView单元大小调整提供了几个选项: 1. Autolayout,2。override sizeThatFits()或3. override prefferedLayoutAttributesFittingattributes()

您可以观看WWDC 2016视频会话219以获取更多信息。

下面的Autolayout选项。

使用文本标签创建了一个UICollectionViewCell子类xib。 在视图控制器创建的collectionView中,添加为子视图,注册xib,设置UICollectionViewFlowLayout,估计大小为1x1。 UICollectionView将开箱即可计算出高度。

class ViewController: UIViewController {
    var collectionView: UICollectionView? {
        didSet {
            let nib = UINib.init(nibName: "Cell", bundle: nil)
            collectionView?.register(nib, forCellWithReuseIdentifier: "Cell")
        }
    }

    let dataSource: [String] = ["test test test test test",
                                "test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test"]

    override func viewDidLoad() {
        super.viewDidLoad()
        let flowLayout = UICollectionViewFlowLayout()
        // Don't miss this line, or collectionView will use autosizing by default
        flowLayout.estimatedItemSize = CGSize(width: 1, height: 1)
        let collection = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout)
        view.addSubview(collection)
        collectionView = collection
        collectionView?.dataSource = self
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
        cell.descriptionLabel.text = dataSource[indexPath.row]
        return cell
    }
}

细胞设置:

@IBOutlet weak var widthLayoutConstraint: NSLayoutConstraint!

override func awakeFromNib() {
    super.awakeFromNib()
    // We dont need autolayout calculation for width and height of the cell so disabling it
    contentView.translatesAutoresizingMaskIntoConstraints = false
    // And adding a constant width constraint
    let width = UIScreen.main.bounds.size.width
    widthLayoutConstraint.constant = width - 24.0 // giving some offsets for the cell: 24 pt
}

另请注意,此设置不适用于iOS< 9。