导航到另一个 ViewController 或从 tableView Cells 执行任何交互不是最佳实践。我更喜欢您使用委托模式来获得所需的功能。
- 在表格视图单元格中声明弱委托。
一个。发送有效载荷。 i,e(所选单元格的索引路径)到 viewController。
- 在 viewController 中执行操作。
通知也可以用于相同的目的,但通常不鼓励使用它们,我们应该尝试在极少数情况下使用它们。
protocol InnerTableCellDelegate: class {
func didSelectedRowWith(indexPath: IndexPath)
}
class InnerTableCell: UITableViewCell {
weak var delegate: InnerTableCellDelegate? = nil
.
.
.
// In tableCellDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let safeDelegate = self.delegate {
safeDelegate.didSelectedRowWith(indexPath: indexPath)
}
}
}
现在您必须在父 viewController 中拥有相同的 tableView 委托和数据源。在 cellForRowAt(...) 方法中,将单元格委托设置为 self。
class ViewController: UIViewController {
// MARK: - TableView Datasouce & Delegates
func cellForRowAt(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let cell: InnerTableCell = tableView.dequeReusableCellWithIdentifier(reusableIdentifier: "InnerTableViewCell", indexPath: IndexPath) as! InnerTableViewCell
cell.delegate = self
return cell
}
}
现在,让您的 viewcontroller 符合 cell 委托并从那里执行操作。
extension ViewController: InnerTableCellDelegate {
func didSelectedRowWith(indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "storyboard", bundle: nil)
let viewC = storyboard.instantiateViewController(withIdentifier: "DestinationViewC") as! DestinationViewC
self.navigationController?.pushViewController(controller, animated: false)
}
}