我有一个表格 View ,其中加载了三个自定义单元格:一个帖子标题单元格、一个帖子图像单元格和一个帖子操作单元格。 see tableview cells here
我目前在 postImage 单元格中有视频的播放按钮,并且工作正常,但是,我想将播放按钮的功能移至用户投票赞成或反对的 postAction 单元格,因此当用户投票时,还会调用播放视频函数(handlePlay)。
新功能:我将 PostActionCell 作为自定义类,并将我的主视图 Controller (HomeVC) 作为处理投票功能的委托(delegate)。
我也有 PostImageCell 作为自定义类,并且我尝试让 HomeVC 成为委托(delegate),当我这样做时,我可以访问我需要的 TableView 数据,但随后我在尝试访问同一个中的 PostImageCell 和 PostActionCell 时遇到了困难地点。
我还尝试使 PostActionCell 成为 PostImageCell 的委托(delegate),这允许我访问我需要的 PostImageCell 类数据,但不能访问 TableView 数据...
那么,我应该如何/在哪里尝试访问这两个自定义类?
这是我的 PostImageCell 协议(protocol):
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...:
//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)
}
}
}
}
最佳答案
您可以使用此扩展程序访问表格 View :
extension UITableViewCell {
var tableView: UITableView? {
return next as? UITableView
}
}
您可以使用此扩展访问单元格的索引路径:
extension UITableViewCell {
var indexPath: IndexPath? {
return tableView?.indexPath(for: self)
}
}
因此,您可以计算玩家单元格索引并使用tableView.cellForRow(at: indexPath)
访问它。
关于ios - 使用 2 个类/委托(delegate) Swift 从另一个单元格控制 UITableView 单元格的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856699/