1

I have created an UICollectionView horizontal scroll through programmatically. UICollectionView cell width is dynamically created based on the content.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! CustomCollectionViewCell
    cell.label.text = dataSource[indexPath.item]
    cell.label.font = UIFont(name: "Helvetica", size: 20.0)

    if currentPageIndex == indexPath.item {

        cell.currentPageIndicator.frame = CGRect(x: 0, y: cell.bounds.height - 2, width: cell.bounds.width, height: 2.5)
        cell.currentPageIndicator.isHidden = false
    }

    return cell

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if let size = cellSizeCache.object(forKey: indexPath as AnyObject) as? NSValue {
        return size.cgSizeValue
    }

    let string = dataSource[indexPath.item]
    let height = collectionView.frame.size.height
    let font = UIFont(name: "Helvetica", size: 20.0)
    var size = string.boundingRect(with: CGSize(width: CGFloat.infinity, height: height), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font!], context: nil).size

    size.width += 20
    size.height += 20

    return size

}

Initially, an UICollectionView is looking fine, even when I scroll horizontally. enter image description here When I start scrolling fast, cell's are overlap with each other. enter image description here

PradeshV
  • 63
  • 9

1 Answers1

0

Your cells are overlapping because the width of the cell is lesser then the size of content. You have two options, first option is to increase the width of cell in storyboard. Second option is to set the size for each cell in collectionview method named "sizeforcellatindexpath", sample method is given below:

    optional func collectionView(_ collectionView: UICollectionView,
              layout collectionViewLayout: UICollectionViewLayout,
         sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

     return size

    }

you can calculate the size of string by using calculation mechanism. Sample for collection in given below:

How to calculate the width of a text string of a specific font and font-size?

Community
  • 1
  • 1
Zohaib Hassan
  • 984
  • 2
  • 7
  • 11