首页 > 解决方案 > UITableViewCells 可以代表吗?

问题描述

我想知道是否可以使 UITableViewCell 符合协议,并将 UITableViewCell 设置为委托。原因是,因为我希望在另一个类中更改某个值时更新一些 UITableViewCells,并且我正在考虑使用协议/委托方法来执行此操作。但是,到目前为止,我还不能成功地将 UITableViewCell 转换为委托。甚至可能吗?

这是我到目前为止的代码:

协议

protocol UploadManagerDelegate: AnyObject {
  func taskWasUpdated(id: String, value: Double)
}

上传管理器类

public final class UploadingManager {
  static var uploadingTasks: Dictionary<String, Double> = [:]
  static weak var uploadDelegate: UploadManagerDelegate

  static func removeTask(id: String) {
    uploadingTasks.removeValue(forKey: id)
  }
  
  static func getTask(id: String) -> Double? {
    if uploadingTasks[id] == nil {
      return nil
    } else {
      return uploadingTasks[id]
    }
  }
  
  static func isUploading(id: String) -> Bool {
    return (uploadingTasks[id] != nil)
  }
  
  static func updateTask(id: String, completion: Double) {
    uploadingTasks[id] = completion
    uploadDelegate?.taskWasUpdated(id: id, value: completion)
  }
}

自定义 UITableViewCell 类

class TrackCell: UITableViewCell, UploadManagerDelegate {

...

override func awakeFromNib() {
  UploadingManager.uploadDelegate = self // Can I do this??
  super.awakeFromNib()
}

...

func taskWasUpdated(id: String, value: Double) {
  if(audioFile?.trackID == id) {
    activityIndicator.setProgress(Float(value), animated: true)
  }
}

标签: iosswiftuitableviewdelegatesprotocols

解决方案


是的,这是可能的,您可以按照此处所述进行符合。

但是在执行此操作之前,您必须考虑某些情况,例如:

  1. 所有单元格都将遵循相同的协议,因此所有单元格上的 activityIndi​​cator 进度更新将始终相同。
  2. 由于 dequeueReusableCell,您需要仅在它们可见时更新单元格

因此,我的建议也与@Hossam 在评论中建议的从 VC(UploadingManager)更新单元格相同。


推荐阅读