【问题标题】:CollectionViewCell Draw RectCollectionViewCell 绘制矩形
【发布时间】:2019-03-20 05:50:24
【问题描述】:

我正在尝试在我的集合视图单元格内绘制一个简单的轮廓圆圈。出于某种原因,只有第一个单元格被绘制,其余的没有显示。

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

我在这里错过了什么?

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    集合视图单元格配置为使用 UICollectionViewDataSource 方法 cellForItemAt() 进行显示。单元格被重复使用,并且不会为每个“新”单元格自动重绘。不要覆盖 draw(rect),而是将子视图添加到单元格并在 cellForItemAt() 中配置子视图。

    【讨论】:

    • 好的,谢谢。我遇到了这个线程,stackoverflow.com/questions/36871544/….... 这不起作用。如本文所示,在 cellForItemAt() 或 collectionViewCell 中
    • 假设这个答案的第一部分是你指的是什么?
    【解决方案2】:

    您可能希望以不同的方式定义您的center 点。 center 点在其superview 坐标系中的点中指定。尝试从其父视图的坐标系转换单元格的 center 点,或者改用单元格的边界并相应地调整 xy 值。

    let center = self.convert(self.center, from: self.superview)
    
    let center = CGPoint(x: bounds.midX, y: bounds.midY)
    

    【讨论】:

    • 是的,我后来意识到了这一点。
    • 这也有效:let center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    【解决方案3】:

    创建了一个符合 UIView() 的新类,在其绘制函数中添加了 bezierPath 信息。然后在 collectionView 单元格中对此类进行子类化。按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 2013-08-26
      • 1970-01-01
      相关资源
      最近更新 更多