首页 > 解决方案 > 表视图委托内的集合视图

问题描述

我在表格行中有一个带有集合视图的表格视图。接下来是结构:

MainViewController.swift:

class MainViewController: UIViewController {
     @IBOutlet weak var customTable: UITableView!
     func callSegue() {
         performSegue(withIdentifier: "customSegue", sender: self)
     }
     override func viewDidLoad() {
          customTable(UINib(nibName: "CustomTableCell", bundle: nil), forCellReuseIdentifier: "TipsTableCell")
     }
}
extension MainViewController: UITableViewDataSource {
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return 1
     }
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableCell", for: indexPath) as! CustomTableCell
          //Fill cell with my data
          return cell
     }
}

CustomTableCell.swift

class CustomTableCell.swift: UITableViewCell {
     @IBOutlet var collectionView: UICollectionView!
     override func awakeFromNib() {
         super.awakeFromNib()
         self.collectionView.dataSource = self
         self.collectionView.delegate = self
         self.collectionView.register(UINib.init(nibName: "CustomTableCell", bundle: nil), forCellWithReuseIdentifier: "CustomTableCell")
     }
}
extension CustomTableCell: UICollectionViewDataSource, UICollectionViewDelegate {
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return dataArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomTableCell", for: indexPath) as! CustomTableCell
 cell.label1.text = dataArray[indexPath.item]
return cell

和我的 CustomCollectionvCell.swift

class CustomCollectionvCell: UICollectionViewCell {
     @IBOutlet weak var label1: UILabel!
     override func awakeFromNib() {
         super.awakeFromNib()
     }

我需要这样的东西:当我点击 label1.text == "Something" 的单元格时,我需要在 MainViewController 中调用 "callSegue" 函数。

标签: swift

解决方案


用来closures解决。

添加一个closurein并在点击 in方法CustomTableCell时调用它,即collectionViewCellcollectionView(_:didSelectItemAt:)

class CustomTableCell: UITableViewCell {
    var handler: (()->())?
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.handler?()
    }
}

MainViewController,设置closurewhile出队CustomTableCell方法tableView(_:cellForRowAt:),即

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableCell", for: indexPath) as! CustomTableCell
    cell.handler = {[weak self] in
        self.callSegue() //here.....
    }
    return cell
}

还要交叉检查seguecustomSeguestoryboard.


推荐阅读