使用 2 类 / delegates Swift 从另一个单元格控制 UITableView 单元格的内容

control the content of UITableView cell from another cell with 2 classes / delegates Swift

我有一个加载了三个自定义单元格的表格视图,一个 post header 单元格,一个 post 图像单元格和一个 post 操作单元格。 see tableview cells here

我目前在 postImage 单元格中有我的视频的播放按钮,它工作正常,但是,我想将播放按钮的功能移动到 postAction 单元格中用户投票是或否,所以当用户投票时,它也会调用播放视频函数(handlePlay)。

新:我将 PostActionCell 作为自定义 class,并将我的家 viewcontroller (HomeVC) 作为代理来处理投票功能。

我也有自定义的 PostImageCell class,我试图让 HomeVC 成为一个委托,当我这样做时我可以访问我需要的 tableview 数据,但后来我在尝试访问PostImageCell 和 PostActionCell 在同一位置。

我还尝试让 PostActionCell 成为 PostImageCell 的委托,这样我就可以访问我需要的 PostImageCell class 数据,但不能访问 tableview 数据...

那么,how/where 我应该尝试访问这两个自定义 classes 吗?

这是我的 PostImageCell 协议:

import UIKit
import AVFoundation

protocol PostImageCellDelegate: class {
   func playVideo(_ cell: PostImageCell)
}

class PostImageCell: UITableViewCell {

   weak var delegate: PostImageCellDelegate?

   @IBOutlet weak var postImage: UIImageView!
   @IBOutlet weak var playButton: UIButton!

   override func awakeFromNib() {
       super.awakeFromNib()
   }

   func playVideoCalled() {
       delegate?.playVideo(self)
   }

   func prepareForReuse(layer: AVPlayerLayer) {
      super.prepareForReuse()
      layer.removeFromSuperlayer()
   }
}

这是我在 HomeVC 上访问 PostActionCell 和 PostImageCell 的尝试,但我似乎无法在需要时访问 PostImageCell...:[=​​15=]

//MARK: - PostActionCell and PostImageCell DELEGATE

extension HomeVC: PostActionCellDelegate, PostImageCellDelegate {

   func playVideo(_ cell: PostImageCell) {

      guard let indexPath = tableView.indexPath(for: cell) else { return }

      handlePlay2(cell, indexPath: indexPath)

   }

   func didTapVoteYesButton(_ voteButton: UIButton, on cell: PostActionCell ) {

      //playVideo( NEED PostImageCell HERE )

      guard let indexPath = tableView.indexPath(for: cell) else { return }

      voteButton.isUserInteractionEnabled = false

      let post = posts[indexPath.section]

      VoteFirebase.setDidVoteYes(!post.didVote, for: post) { (success) in
         defer {
            voteButton.isUserInteractionEnabled = true
         }

         guard success else { return }

         post.yesCount += !post.didVote ? 1 : -1
         post.voteCount += !post.didVote ? 1 : -1
         post.didVote = !post.didVote

         guard let cell = self.tableView.cellForRow(at: indexPath) as? PostActionCell
            else { return }

          DispatchQueue.main.async {
             self.configureCell(cell, with: post)
          }
       }
    }
}

您可以使用此扩展程序访问 table 视图:

extension UITableViewCell {
    var tableView: UITableView? {
        return next as? UITableView
    }
}

并且您可以使用此扩展名访问单元格的 indexPath:

extension UITableViewCell {
    var indexPath: IndexPath? {
        return tableView?.indexPath(for: self)
    }
}

因此您可以计算玩家单元格索引并使用 tableView.cellForRow(at: indexPath) 访问它。