【问题标题】:prepareForReuse is not working properly with imageViewprepareForReuse 无法与 imageView 一起正常工作
【发布时间】:2017-12-14 00:23:52
【问题描述】:

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

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

【问题讨论】:

  • 您添加了subLayer。在 prepareForReuse 中,添加另一个子层,然后将其删除。但这并没有删除第一个。
  • @Larme 好的,我用全局变量更新了函数。但现在我什至没有得到一个底部边框。
  • 请更新问题中的代码以显示您现在所做的 - “全局变量”听起来令人担忧,边框层应该是单元格的属性

标签: ios swift uicollectionview prepareforreuse


【解决方案1】:
self.imageView?.layer.sublayers?.forEach { $0.removeFromSuperlayer() }

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2013-02-06
  • 2019-02-02
  • 2021-10-15
  • 2016-07-05
  • 2016-09-13
  • 2014-08-23
相关资源
最近更新 更多