我有一个播客播放器应用程序的两个文件项目。我的目标是,当用户单击播放按钮(加载在nib单元格中(时,将显示带有播放/暂停的PodcastPlayerView(添加到视图控制器中的StoryBoard中(。
.
├── _DetailViewController.swift
│ ├── AVPlayer
│ ├── PodcastPlayerView (full-screen player view)
│ └── setupPodcastPlayer (setting player's URL & hide/unhide PodcastPlayerView)
│
├── _PodcastViewCell.swift (File Owner of the nib)
│ ├── url (Podcast URL of the cell)
└── └── @IBAction playPodcast (the play button in a cell)
这是PodcastViewCell.swift中运行的大部分代码。获取单元格的itemId,找到其播客链接,然后将其传递给视图控制器。
protocol PodcastViewCellDelegate {
func podcastButtonClicked(podcastUrl: String)
}
class PodcastViewCell: UICollectionViewCell {
weak var delegate: PodcastViewCellDelegate?
@IBAction func playPodcast(_ sender: Any) {
if let itemOffset = allItems?.itemListv2.firstIndex(where: {$0.itemId == itemAuthor?.itemId}) {
podcastLink = allItems?.itemListv2[itemOffset].podcastsound
}
let url = podcastLink ?? " "
delegate?.podcastButtonClicked(podcastUrl: URL)
}
}
这是视图控制器代码,包含Podcast Player UIView、AVPlayer Player、PodcastViewCells的集合视图等。我还在代码中添加了可以和不能隐藏/取消隐藏PodcastPlayerView的行。当我在视图被取消隐藏的情况下运行应用程序时,视图是可见的,并且位于它应该位于的位置。但我仍然无法在我提到的行中取消隐藏它。这就像视图加载并被破坏一样。。。
class DetailViewController: BaseViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var podcastPlayerView: UIView!
var podcastLink: String = ""
static var itemId = "0"
var player: AVPlayer?
var playerItem: AVPlayerItem?
var timeObserverToken: Any?
var played = false
override func viewDidLoad() {
super.viewDidLoad()
self.podcastPlayerView.isHidden = false "<-------- Unhiding/hiding process successful in this step"
}
override func viewWillDisappear(_ animated: Bool) {
showPodcastButton = false
player?.pause()
player?.replaceCurrentItem(with: nil)
player = nil
}
func setupPodcastPlayer(link: String) {
player?.pause()
player?.replaceCurrentItem(with: nil)
player = nil
if !played {
if link != "" {
playerItem = AVPlayerItem( url:NSURL( string:link )! as URL )
player = AVPlayer(playerItem:playerItem)
player!.rate = 1.0;
player!.play()
played = true
podcastPlay()
} else {
"link empty"
}
} else {
player?.replaceCurrentItem(with: nil)
played = false
}
}
func podcastPlay() {
self.podcastPlayerView.isHidden = false "<---- If I try to unhide here, app crashes."
"Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value"
}
}
extension DetailViewController: PodcastViewCellDelegate {
func podcastButtonClicked(podcastUrl: String) {
podcastPlayerView.isHidden = false
setupPodcastPlayer(link: podcastUrl)
}
}
谢谢你的建议,祝你今天愉快!
出现问题
DetailViewController().setupPodcastPlayer(link: url)
这个DetailViewController()
是一个新实例,而不是呈现的实例,挂接实际显示的实例,并根据需要通过委托或通知(如果需要(更改其属性
编辑:单元格内部
weak var delegate: DetailViewController?
并将其设置在cellForRowAt
中
cell.delegate = self