UICollectionView的最小高度(快速)

时间:2019-02-04 20:40:14

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我正在尝试使用自定义UICollectionView在Swift中创建一个简单的UICollectionViewCell。我的UICollectionViewController中有以下方法可以设置单元格的大小;

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width  = (collectionView.frame.width  / 3) - 10
    let height = CGFloat(170)

    return CGSize(width: width, height: height)
}


然后,我为单元格设置约束如下:

private func setImageViewConstraints() {
    itemImageView.translatesAutoresizingMaskIntoConstraints = false // enables Auto-Layout

    itemImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true      // center horizontally
    itemImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true // 8pt from top of cell

    // 1:1 Aspect Ratio
    itemImageView.widthAnchor.constraint(equalToConstant: (self.frame.width - 4)).isActive = true
    itemImageView.heightAnchor.constraint(equalTo: itemImageView.widthAnchor).isActive = true
}

private func setupLabelConstraints() {
    itemLabel.translatesAutoresizingMaskIntoConstraints = false

    itemLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true

    itemLabel.leftAnchor.constraint(equalTo: itemImageView.leftAnchor, constant: 0).isActive = true
    itemLabel.rightAnchor.constraint(equalTo: itemImageView.rightAnchor, constant: 0).isActive = true

    itemLabel.topAnchor.constraint(equalTo: itemImageView.bottomAnchor, constant: 4).isActive = true
    itemLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -4).isActive = true
}


但是,单元格的高度会有所变化,例如,取决于其内容的高度;

How my Collection View looks

如何设置单元格的高度,使它们都相同? 谢谢!

0 个答案:

没有答案