在你的自定义UICollectionViewCell中添加tap手势识别器:
class CustomCell: UICollectionViewCell {
// 添加你的UI元素
// ...
weak var parentViewController: UIViewController?
override init(frame: CGRect) {
super.init(frame: frame)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cellTapped)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func cellTapped() {
parentViewController?.performSegue(withIdentifier: "YourSegueIdentifier", sender: self)
}
}
然后,在你的UICollectionViewDataSource协议的cellForItemAt方法中设置parentViewController:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCellIdentifier", for: indexPath) as! CustomCell
cell.parentViewController = self
return cell
}
最后,在你的UIViewController(即Player)中使用prepareForSegue方法传递数据:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourSegueIdentifier" {
if let cell = sender as? CustomCell {
let indexPath = collectionView.indexPath(for: cell)
// 在这里传递你的数据到Player视图控制器
// ...
}
}
}