jstira
jstira

Reputation: 41

Error: Value of type 'CGRect' has no member 'center'

Trying to create layout for a circular collection view. Everything seems well apart from when I try to center the position.

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)
                    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).")
            }
        }

Expected to run but instead receive the error: Value of type 'CGRect' has no member 'center'. This error is on the line;

var position = layoutCircleFrame.center

Upvotes: 2

Views: 5885

Answers (2)

rmaddy
rmaddy

Reputation: 318824

There is no center property in CGRect, hence the error. It's a property of UIView.

You could do:

var position = CGPoint(x: layoutCircleFrame.midX, y: layoutCircleFrame.midY)

Or, as seen here, you can add a center property to CGRect via an extension.

Upvotes: 0

matt
matt

Reputation: 535305

What I do is add this extension to my code (at the top level of a file):

extension CGRect {
    var center : CGPoint {
        return CGPoint(x:self.midX, y:self.midY)
    }
}

Upvotes: 3

Related Questions