简体   繁体   中英

CollectionViewCell Draw Rect

I'm trying to draw a simple outlined circle inside my collection view cells. For some reason, only the first cell is being draw, the rest are not showing.

class UserCell: UICollectionViewCell {

    override func draw(_ rect: CGRect) {

        let center = CGPoint(x: self.center.x - 1, y: 41)

        let circularPath = UIBezierPath()
        circularPath.addArc(withCenter: center, radius: 36, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: true)

        UIColor.red.setStroke()
        circularPath.lineWidth = 2
        circularPath.stroke()


    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.white
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

在此输入图像描述

What am I missing here?

Collection view cells are configured for display using UICollectionViewDataSource method cellForItemAt(). The cells are reused and won't automatically redraw for each 'new' cell. Instead of overriding draw(rect), add subviews to the cell and configure the subviews in cellForItemAt().

You might want to define your center point differently. The center point is specified in points in the coordinate system of its superview . Either try convert the cell's center point from its superview's coordinate system or use the bounds of the cell instead and adjust the x and y values accordingly.

let center = self.convert(self.center, from: self.superview)

let center = CGPoint(x: bounds.midX, y: bounds.midY)

CollectionViewCell

Created a new class conforming to UIView(), added the bezierPath info inside its draw function. Then subclassed this class inside the collectionView cell. Works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM