prepareForReuse与imageView无法正常工作

时间:2017-07-10 10:02:00

标签: ios swift uicollectionview prepareforreuse

每当我的isLive函数返回true时,我都会尝试向imageview添加底部边框。我检查了部件,它只执行一次。但是,有多个单元格具有蓝色底部边框。此代码如下所示:

DispatchQueue.main.async {
    if CommunityViewController().isLive(startTime: startTime, endTime: endTime, name: self.cellChannel[indexPath.row].communityName){
        cell.imageView.addBottomBorderWithColor(color: constants.waterblue, width: 3)
        }
    }

我的addBottomBorderWithColor是一个扩展名,如下所示:

  func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
    self.layer.addSublayer(border)
}

据我所知,我需要删除prepareForReuse函数中的下边框。我试图用另一个扩展名删除它:

 func removeBottomBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
    self.layer.addSublayer(border)
    border.removeFromSuperlayer()
}

prepareForReuse是正确的方法还是我需要以其他方式设置它?

我用以下方式调用prepareForReuse:

  override func prepareForReuse() {
    self.imageView?.removeBottomBorderWithColor(color: constants.waterblue, width:3)
}

1 个答案:

答案 0 :(得分:1)

self.imageView?.layer.sublayers?.forEach { $0.removeFromSuperlayer() }

尝试直接使用此代码以准备重用方法。在cellForItemAtIndexPath方法中添加图层。