Collection View Cells have incorrect content size

≡放荡痞女 提交于 2019-11-29 16:46:59

I do encounter the same problem with my previous project. I managed to solve the problem by using this library: Snapkit . import the library in pod and implement it in cellForItemAtIndexPath

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ChartViewCell

    let width = self.view.bounds.size.width / 24
    cell.overlay.snp_makeConstraints { (make) -> Void in
        make.width.equalTo(width)
        make.height.equalTo(width)
    }
    cell.setColor(colorArray[indexPath.section][indexPath.row])
    cell.overlay?.image = cell.whichColor.toImage()
    return cell
}

Just put only top and leading constraint on the imageView in the storyboard. Hope it helps.

I fixed the problem by doing the following:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ChartViewCell
    cell.setColor(colorArray[indexPath.section][indexPath.row])
    cell.overlay?.image = cell.whichColor.toImage()

    let screenRect: CGRect = collectionView.bounds
    let screenWidth: CGFloat = screenRect.size.width
    let cellWidth: CGFloat = screenWidth / 24
    cell.singleCellWidthConstraint.constant = cellWidth - 8
    cell.overlayWidthConstraint.constant = cellWidth - 4
    return cell
}

I just added a width constraint for the images, and added an outlet to them in the cells class. Then I deleted the bottom and right constraints and added a 1:1 constraint on the images. It worked like a charm on all devices!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!