通过委托进行。我在collection view上做了,你也可以在tableview上做。请按照以下步骤操作
1 .在您的自定义单元类中创建一个 delegateHandler 并覆盖您的 awakeFromNib() 方法。例如
protocol BibleReadingSliderProtocol: class {
func addThisViewControllerAsChild(audioViewController :AudioViewController)
}
class BibleReadingSliderCollectionCell: UICollectionViewCell {
@IBOutlet weak var containerView: UIView!
var audioVC = AudioViewController()
weak var bibleReadingSliderDelegate:BibleReadingSliderProtocol?
override func awakeFromNib() {
super.awakeFromNib()
print("Awake call from cell")
// Initialization code
let storyboard = UIStoryboard(name: "Main", bundle: nil)
audioVC = storyboard.instantiateViewController(withIdentifier: "AudioViewController") as! AudioViewController
audioVC.view.frame = self.containerView.bounds
self.containerView.addSubview(audioVC.view)
if self.bibleReadingSliderDelegate != nil {
self.bibleReadingSliderDelegate?.addThisViewControllerAsChild(audioViewController: audioVC)
}
}
}
在您使用此客户单元格(表格视图或集合视图)的 ViewController 中定义委托处理程序
func addThisViewControllerAsChild(audioViewController: AudioViewController) {
self.addChildViewController(audioViewController);
}
并且不要忘记在 cellForItemAt/cellForRowAt 中将您的委托设置为此视图控制器
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let imageSliderCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! BibleReadingSliderCollectionCell
imageSliderCollectionViewCell.bibleReadingSliderDelegate = self
return imageSliderCollectionViewCell
}