Last active
April 9, 2020 12:55
-
-
Save laevandus/2db2c95b62907f364948becf5358679e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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).") | |
} | |
} | |
} |
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
This line 'var position = layoutCircleFrame.center' is giving error:
Value of type 'CGRect' has no member 'center'
Do you have its solution?