UICollectionView Cell Overlap

后端 未结 5 578
别跟我提以往
别跟我提以往 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:32

    I used mdewitt's answer, converted it to swift 3 and i works great! For anyone interested:

    class CollectionViewOverlappingLayout: UICollectionViewFlowLayout {
    
    var overlap: CGFloat = 30
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        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)
    }
    }
    

提交回复
热议问题