Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
private var layoutCircleFrame = CGRect.zero
private let layoutInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
private let itemSize = CGSize(width: 100, height: 100)
private var itemLayoutAttributes = [UICollectionViewLayoutAttributes]()
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
itemLayoutAttributes.removeAll()
layoutCircleFrame = CGRect(origin: .zero, size: collectionViewContentSize)
.inset(by: layoutInsets)
.insetBy(dx: itemSize.width / 2.0, dy: itemSize.height / 2.0)
.offsetBy(dx: collectionView.contentOffset.x, dy: collectionView.contentOffset.y)
.insetBy(dx: -collectionView.contentOffset.x, dy: -collectionView.contentOffset.y)
for section in 0..<collectionView.numberOfSections {
switch section {
case 0:
let itemCount = collectionView.numberOfItems(inSection: section)
itemLayoutAttributes = (0..<itemCount).map({ (index) -> UICollectionViewLayoutAttributes in
let angleStep: CGFloat = 2.0 * CGFloat.pi / CGFloat(itemCount)
// CGRect extension for center and innerRadius: https://gist.github.com/laevandus/07955ff394984bda6de4922734429c84
var position = layoutCircleFrame.center
position.x += layoutCircleFrame.size.innerRadius * cos(angleStep * CGFloat(index))
position.y += layoutCircleFrame.size.innerRadius * sin(angleStep * CGFloat(index))
let indexPath = IndexPath(item: index, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(center: position, size: itemSize)
return attributes
})
default:
fatalError("Unhandled section \(section).")
}
}
}
@ShikhaSingla

This comment has been minimized.

Copy link

@ShikhaSingla ShikhaSingla commented Apr 9, 2020

This line 'var position = layoutCircleFrame.center' is giving error:
Value of type 'CGRect' has no member 'center'

Do you have its solution?

@laevandus

This comment has been minimized.

Copy link
Owner Author

@laevandus laevandus commented Apr 9, 2020

import CoreGraphics
extension CGRect {
    init(center: CGPoint, size: CGSize) {
        self.init(x: center.x - size.width / 2.0, y: center.y - size.height / 2.0, width: size.width, height: size.height)
    }
    
    var center: CGPoint { return CGPoint(x: midX, y: midY) }
}

extension CGSize {
    var innerRadius: CGFloat { return min(width, height) / 2.0 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment