【发布时间】:2018-10-17 13:58:06
【问题描述】:
我有一个表格视图,其中加载了三个自定义单元格、一个帖子标题单元格、一个帖子图像单元格和一个帖子操作单元格。 see tableview cells here
我目前在 postImage 单元格中有我的视频的播放按钮,它工作正常,但是,我想将播放按钮的功能移动到用户投票是或否的 postAction 单元格,所以当用户票,它还会调用播放视频函数(handlePlay)。
新功能:我将 PostActionCell 作为自定义类,并将我的主视图控制器 (HomeVC) 作为代理来处理投票功能。
我也有 PostImageCell 作为自定义类,我试图让 HomeVC 成为委托,当我这样做时,我可以访问我需要的 tableview 数据,但是我在尝试访问 PostImageCell 和 PostActionCell 时遇到了困难地点。
我还尝试让 PostActionCell 成为 PostImageCell 的代表,这样我就可以访问我需要的 PostImageCell 类数据,但不能访问 tableview 数据...
那么,我应该如何/在哪里尝试访问这两个自定义类?
这是我的 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...:
//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)
}
}
}
}
【问题讨论】:
-
这是代表的工作。将数据源用作两个单元之间的通信层。
-
您可以使用 PostActionCell 注册回调。当用户投票时,只需调用回调处理程序块,并在该块内调用 handlePlay 方法。
-
@TamásSengel 感谢您提供该问题的链接,我一直在努力解决这个问题。我被困在如何“使用数据源作为两个单元之间的通信层”你能看看更新的问题吗?谢谢!
-
@TamásSengel 跟进,在我上面的代码中,我是否应该让我的 HomeVC 扩展也符合我的 PostImageCell 协议,并尝试以这种方式访问我的 PostImageCell?
标签: ios swift uitableview delegates swift-protocols