【问题标题】:How to create UICollectionView like zig-zag如何像之字形一样创建 UICollectionView
【发布时间】:2021-12-07 23:01:42
【问题描述】:

我附上了我想要的屏幕显示。我尝试了下面的代码,但没有得到显示结果

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ZigZagCollectionCell", for: indexPath) as! ZigZagCollectionCell
        
        cell.setUpCell()
        
        if indexPath.row % 2 == 0 {
            cell.viewBG.backgroundColor = UIColor.red
        } else {
            cell.viewBG.backgroundColor = UIColor.green
        }
        
        return cell
    }

我想要这种类型的集合视图。提前致谢。

【问题讨论】:

  • 两个选项 1. 子类UICollectionViewFlowLayout 2. 使用compositional flow layout 你会发现很多教程
  • 谢谢。有什么参考链接可以帮助我吗?
  • @KamleshShinarakhiya 请查看链接raywenderlich.com/…

标签: ios swift iphone uicollectionview


【解决方案1】:

正如@Sandeep Bhandari 所说,子类UICollectionViewFlowLayout

然后,你给每个项目自己的框架。

1、首先在override public func prepare()

计算每个项目的框架,

& 使用private var cache = [IndexPath: UICollectionViewLayoutAttributes]() 存储,

这是设置每个项目的框架的关键步骤。

2、其次,为每个item提供框架数据。

override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
       return cache[indexPath]
}

3、第三,提供所有的frame数据,包括item/decoration view/supplemental view

override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    guard let _ = collectionView else { return nil }
    
    visibleLayoutAttributes.removeAll(keepingCapacity: true)
   
      for (_, attributes) in cache {
        attributes.transform = .identity
        if attributes.frame.intersects(rect) {
            visibleLayoutAttributes.append(attributes)
        }
      }
    
    return visibleLayoutAttributes
  }

这里是相关示例github repo

【讨论】:

    猜你喜欢
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多