Silvering
Silvering

Reputation: 787

Space between cells UICollectionViewLayout

I'm currently using this TreeMap framework layout fully coded in Swift : https://github.com/yahoo/YMTreeMap

I created my own Layout class in order to customize cells like this :

import UIKit

class Layout: UICollectionViewLayout {

    var rects = [CGRect]() {
        didSet {
            invalidateLayout()
        }
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }

    override var collectionViewContentSize: CGSize {
        return self.collectionView?.frame.size ?? .zero
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            attrs.frame = rects[indexPath.item]
        return attrs
    }

    open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        var index = 0

        return rects.compactMap { (itemRect: CGRect) -> UICollectionViewLayoutAttributes? in
            let attrs = rect.intersects(itemRect) ?
                self.layoutAttributesForItem(at: IndexPath(item: index, section: 0)) : nil

            index += 1

            return attrs
        }

    }
}

However I can not manage to insert spaces between cells. I tried many thing like minimumLineSpacingForSectionAt but no success...

Here is what I have : digitalblend.fr/today.png and this is what is need : digitalblend.fr/needed.png

Any idea? Thanks a lot in advance!

Upvotes: 0

Views: 66

Answers (1)

user5924595
user5924595

Reputation:

You may want to change the constraints that define your custom UICollectionViewCell layout. See the example that comes with YMTreeMap. In target YMTreeMap-iOS by changing the following code lines in override init(frame: CGRect):

    colorView.widthAnchor.constraint(equalTo: contentView.widthAnchor, constant: -1.0).isActive = true
    colorView.heightAnchor.constraint(equalTo: contentView.heightAnchor, constant: -1.0).isActive = true

to

    colorView.widthAnchor.constraint(equalTo: contentView.widthAnchor, constant: -8.0).isActive = true
    colorView.heightAnchor.constraint(equalTo: contentView.heightAnchor, constant: -8.0).isActive = true

You can get this view:

enter image description here

Upvotes: 1

Related Questions