首页 > 解决方案 > PrepareForReuse() 重置 UIView 宽度不起作用

问题描述

我现在被困了一段时间,虽然我想我知道是什么问题,但我仍然无法解决它。我正在使用 tableView ,每个单元格都有倒计时栏动画。每个单元格都有用户设置的自定义持续时间。然后随着时间的流逝,条形动画会滑动。

CADisplayLink用来运行这个动画,这段代码写在控制器文件中,我只是随着时间的推移改变 UIView 的宽度:

@objc func handleProgressAnimation() {
    let currenttime = Date()
    let elapsed = currenttime.timeIntervalSince(animationStartDate)
    let totalWidth: Double = 400.0
    print(elapsed)
    let arrayLength = durationBar.count
    var i: Int = 0
    
    
    
    for  _ in 0..<arrayLength {
       let indexPath = IndexPath(row: i, section: 0)
       let percentage = (elapsed / Double(durationBar[i].durationTime))
       let newWidth = Double(totalWidth  - (totalWidth * percentage))
        durationBar[i].width = newWidth
        if (percentage < 1)
        {
            if let cell = listTableView.cellForRow(at: indexPath) as! listTableViewCell? {
                cell.timeRemainingView.frame.size.width = CGFloat(durationBar[indexPath.row].width)
            }
        }
        else {
            if let cell = listTableView.cellForRow(at: indexPath) as! listTableViewCell? {
                cell.timeRemainingView.frame.size.width = 400
                cell.timeRemainingView.isHidden = true
            }
        }
        i = i + 1
    }
 
}

当所有的条都在减少时,一切都很好,但是随着一个单元格的时间完成,UIView 宽度变为零,然后当用户滚动该单元格时,该单元格被重用,这使得进度条从还有时间的其他单元格中消失。

我正在使用 prepareforsegue() 方法将条形的宽度重置为 400(默认值),但这似乎不起作用。

这是cellforRow代码:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellid, for: indexPath) as! listTableViewCell
    cell.testlabel.text = "\(duration[indexPath.row].durationTime)"
    cell.timeRemainingView.frame.size.width = CGFloat(durationBar[indexPath.row].width)
    
    return cell
    
}

这是PrepareForReuse()

 override func prepareForReuse() {
    super.prepareForReuse()
    self.timeRemainingView.frame.size.width = 400
    self.timeRemainingView.isHidden = false
}

在此处输入图像描述

这是一个屏幕截图。您可以在某些单元格中看到时间已到,但在其他单元格中仍有剩余时间,但进度条已消失。

标签: iosswiftuitableviewreusability

解决方案


您必须重新设置框架。width是一个get-only属性。


推荐阅读