0

我已通過編程創建了一個UICollectionView水平滾動。 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看起來很好,即使我水平滾動。 enter image description here 當我開始快速滾動時,單元格彼此重疊。 enter image description here

回答

0

您的單元格重疊,因爲單元格的寬度小於內容的大小。您有兩個選項,第一個選項是增加故事板中單元格的寬度。第二個選項是設置大小爲的CollectionView方法的每個小區名爲「sizeforcellatindexpath」,下面的示例方法中給出:

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?