UICollectionView Cell Overlap

后端 未结 5 613
别跟我提以往
别跟我提以往 2020-12-31 06:52

I have a horizontal UICollectionView. I want to make the cells overlap each other by a certain amount of 60 pixels so that the second cells overlaps the first by 60 pixels a

5条回答
  •  误落风尘
    2020-12-31 07:16

    Based on Maik Fruhner's answer. To use:

    let someCollectionView = UICollectionView(frame: ,
                                collectionViewLayout: CollectionViewOverlappingLayout())
    

    Code for the custom layout:

    class CollectionViewOverlappingLayout: UICollectionViewFlowLayout {
    
      var overlap: CGFloat = 14
    
    
      override init() {
        super.init()
        self.sharedInit()
      }
      required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.sharedInit()
      }
      func sharedInit(){
        self.scrollDirection = .horizontal
        self.minimumInteritemSpacing = 0
      }
    
      override var collectionViewContentSize: CGSize{
        let xSize = CGFloat(self.collectionView!.numberOfItems(inSection: 0)) * self.itemSize.width
        let ySize = CGFloat(self.collectionView!.numberOfSections) * self.itemSize.height
    
        var contentSize = CGSize(width: xSize, height: ySize)
    
        if self.collectionView!.bounds.size.width > contentSize.width {
          contentSize.width = self.collectionView!.bounds.size.width
        }
    
        if self.collectionView!.bounds.size.height > contentSize.height {
          contentSize.height = self.collectionView!.bounds.size.height
        }
    
        return contentSize
      }
    
      override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    
        let attributesArray = super.layoutAttributesForElements(in: rect)
        let numberOfItems = self.collectionView!.numberOfItems(inSection: 0)
    
        for attributes in attributesArray! {
          var xPosition = attributes.center.x
          let yPosition = attributes.center.y
    
          if attributes.indexPath.row == 0 {
            attributes.zIndex = Int(INT_MAX) // Put the first cell on top of the stack
          } else {
            xPosition -= self.overlap * CGFloat(attributes.indexPath.row)
            attributes.zIndex = numberOfItems - attributes.indexPath.row //Other cells below the first one
          }
    
          attributes.center = CGPoint(x: xPosition, y: yPosition)
        }
    
        return attributesArray
      }
    
      override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return UICollectionViewLayoutAttributes(forCellWith: indexPath)
      }
    }
    

    Works with swift 5 (and probably 4.x).

提交回复
热议问题