【问题标题】:UICollectionView dynamic cell overlap issueUICollectionView 动态单元格重叠问题
【发布时间】:2017-05-08 19:26:14
【问题描述】:

我以编程方式创建了一个UICollectionView 水平滚动。 UICollectionView 单元格宽度是根据内容动态创建的。

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

}

最初,UICollectionView 看起来不错,即使我水平滚动。 当我开始快速滚动时,单元格彼此重叠。

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout


    【解决方案1】:

    您的单元格重叠,因为单元格的宽度小于内容的大小。您有两个选择,第一个选择是增加情节提要中单元格的宽度。第二个选项是在名为“sizeforcellatindexpath”的collectionview方法中设置每个单元格的大小,示例方法如下:

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

    您可以使用计算机制来计算字符串的大小。收集样本如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多