簡體   English   中英

CollectionViewCell Draw Rect

[英]CollectionViewCell Draw Rect

我正在嘗試在我的集合視圖單元格中繪制一個簡單的輪廓圓圈。 由於某種原因,只有第一個單元格正在繪制,其余單元格沒有顯示。

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

在此輸入圖像描述

我在這里錯過了什么?

使用UICollectionViewDataSource方法cellForItemAt()將集合視圖單元格配置為顯示。 這些單元格將被重用,並且不會為每個“新”單元格自動重繪。 而不是覆蓋draw(rect),將子視圖添加到單元格並在cellForItemAt()中配置子視圖。

您可能希望以不同方式定義center center在其超視圖的坐標系中的點中指定。 嘗試從超視圖的坐標系轉換單元格的center ,或者使用單元格的邊界,並相應地調整xy值。

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

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

CollectionViewCell

創建了一個符合UIView()的新類,在其draw函數中添加了bezierPath信息。 然后在collectionView單元格中繼承此類。 按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM