我正在制作一个类似instagram的应用,我想在其中显示视频的封面图像,然后在轻按“播放”按钮(在图像上)时,将播放视频。我可以根据需要创建和显示帖子,但是,当我点击“播放”按钮时,视频会播放(我可以听到音频),但是看不到。
我正在尝试在第一种情况下显示视频
我正在@bjc函数中的tableView外部处理播放按钮功能。
我认为我的问题是将playerLayer.frame设置为所需的单元格/视图,但是我不确定。我将不胜感激任何帮助。这是我的代码。谢谢!
使用解决方案更新: 多亏了在正确方向上的微调,我才知道要访问表格视图的单元格,我需要使用sender属性。在这种情况下,sender.superview给了我尝试访问的视图。
下面更新了代码,并进行了更正。感谢您的帮助!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.section]
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "PostHeaderCell") as! PostHeaderCell
cell.userProfileImage.sd_setImage(with: post.userPhotoURL, placeholderImage: #imageLiteral(resourceName: "NinjaIcon"), options: [], completed: nil)
cell.usernameLabel.text = post.username
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "PostImageCell") as! PostImageCell
cell.postImage.sd_setImage(with: post.photoURL, placeholderImage: #imageLiteral(resourceName: "photo-7"), options: [], completed: nil)
cell.playButton.isHidden = false
cell.playButton.addTarget(self, action: #selector(handlePlay), for: .touchUpInside)
cell.playButton.tag = indexPath.section
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "PostActionCell") as! PostActionCell
cell.delegate = self
configureCell(cell, with: post)
return cell
default:
fatalError("Error: unexpected indexPath")
}
}
@objc func handlePlay(sender: UIButton!) {
let cell = sender.superview
let tag = sender.tag
let post = posts[tag]
let text = post.postText
let videoURLString = post.videoURL
let player = AVPlayer(url: videoURLString!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = cell.postImage.bounds
cell.postImage.layer.addSublayer(playerLayer)
player.play()
// test to make sure the right video is playing
print("for text: ",text)
print("Attempting to Play: ",videoURLString )
}