重新加载数据后未调用UICollectionViewCell draw()方法

时间:2019-01-17 17:29:22

标签: ios swift uicollectionview

我在项目中使用的是UICollectionView,但是它没有为重用的单元绘制单元格。以为我在应用程序打开时有20个单元格,绘制方法被调用了20次。然后我将单元格的数量更改为30,然后重新加载CollectionView,然后draw方法仅被调用10次。我想调用draw方法30次,因为我在该方法中对单元格做了一些操作(添加图像)。

注意:我在iPhone 5s(iOS 10.3.3)中进行了测试

GameCollectionViewCell类下方用作CollectionView的自定义单元格

extension GameCollectionViewCell {

    override func draw(_ rect: CGRect) {

                var princess : UIImageView = UIImageView(image: UIImage(named: "CategoryImages/"+card!.contentImage)?.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0 )))

                var size : CGSize = CGSize(width: rect.size.width-1.8, height: rect.size.height-1.8)
                var origin : CGPoint = CGPoint(x: rect.origin.x+0.9, y: rect.origin.y+0.9)
                var princessRect : CGRect = CGRect(origin: origin, size: size)

                princess.frame = princessRect
                princess.layer.masksToBounds =  true
                princess.layer.cornerRadius = 2;

                contentView.addSubview(princess)

            }
        }

3 个答案:

答案 0 :(得分:0)

的确,您不应该像在控制器的lifeCycle方法中所做的那样覆盖扩展中的方法(例如viewDidLoad()。还请注意,在大多数情况下,您应该调用其{ {1}}。改为创建子类。

在子类super.someFunc()中添加子视图时,请将您的代码放入init方法中:

UICollectionViewCell

如果要更改视图图层中的任何内容,可以覆盖override init(frame: CGRect) { super.init(frame: frame) }

layoutSubviews()

我希望这会有所帮助。

答案 1 :(得分:0)

我的收藏夹视图存在相同的问题,最好的解决方案是在您的GameCollectionViewCellupdateView()中添加功能并将UI元素添加到子视图

func updateView() {
    var princess : UIImageView = UIImageView(image: UIImage(named: "CategoryImages/"+card!.contentImage)?.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0 )))

            var size : CGSize = CGSize(width: rect.size.width-1.8, height: rect.size.height-1.8)
            var origin : CGPoint = CGPoint(x: rect.origin.x+0.9, y: rect.origin.y+0.9)
            var princessRect : CGRect = CGRect(origin: origin, size: size)

            princess.frame = princessRect
            princess.layer.masksToBounds =  true
            princess.layer.cornerRadius = 2;

            addSubview(princess)
}

在为indexpath创建单元格的同时在viewcontroller中调用上述方法

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! GameCollectionViewCell
    cell.updateView()       
    return cell
}

答案 2 :(得分:0)

非常感谢@RobertDresler。他救了我的一天。重新加载CollectionView后,如果调用setNeedsDisplay()方法,则会调用draw()方法。请检查以下内容。

override func prepareForReuse() {

        super.prepareForReuse()
        setNeedsDisplay()

    }
相关问题