简体   繁体   English

CollectionViewCell Draw Rect

[英]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(). 使用UICollectionViewDataSource方法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(). 而不是覆盖draw(rect),将子视图添加到单元格并在cellForItemAt()中配置子视图。

You might want to define your center point differently. 您可能希望以不同方式定义center The center point is specified in points in the coordinate system of its superview . center在其超视图的坐标系中的点中指定。 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. 尝试从超视图的坐标系转换单元格的center ,或者使用单元格的边界,并相应地调整xy值。

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. 创建了一个符合UIView()的新类,在其draw函数中添加了bezierPath信息。 Then subclassed this class inside the collectionView cell. 然后在collectionView单元格中继承此类。 Works as expected. 按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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