我在tableView单元格中有一个collectionView。我想点击collectionView单元格并转到带有传入信息的detailTableView。我没有太多的工作。做了一些研究,它表明tableView单元既没有故事板也没有navigationController。我如何能够将数据传递到detailTableView。这是我的实现可能不正确
class PopularTableViewCell: UITableViewCell {
var books = [CKRecord]()
var detailViewController: DetailViewController!
}
extension PopularTableViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let record = books[indexPath.row]
let storyBoard = UIStoryboard(name: "Home", bundle: nil)
if let detailVC = storyBoard.instantiateViewController(withIdentifier: "DetailVC") as? DetailViewController {
detailVC.bookRecord = record
detailViewController.navigationController?.pushViewController(detailVC, animated: true)
}
}
}
答案 0 :(得分:3)
您应该从包含tableview的根视图控制器推送视图控制器:
self.navigationController.pushViewController(detailVC, animated: true)
集合视图中的数据可以使用自定义委托传递,例如:
protocol CustomDelegate: class {
func didSelectItem(record: CKRecord)
}
weak var delegate: CustomDelegate?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let record = books[indexPath.row]
delegate?.didSelectItem(record: record)
}
然后在tableview单元格中另一位代表:
extension TableViewCell: CustomDelegate {
func didSelectItem(record: CKRecord) {
delegate?.didSelectItem(record: record)
}
}
最后在视图控制器中:
extension ViewController: CustomDelegate {
func didSelectItem(record: CKRecord) {
let storyBoard = UIStoryboard(name: "Home", bundle: nil)
if let detailVC = storyBoard.instantiateViewController(withIdentifier: "DetailVC") as? DetailViewController {
detailVC.bookRecord = record
self.navigationController?.pushViewController(detailVC, animated: true)
}
}
}
PS:不要忘记连接代表,如:
cell.delegate = self
答案 1 :(得分:0)
您可以在集合视图单元格上创建一个委托,然后在它被点击时通知表格视图,然后您可以随后执行任何操作。
只是拥有集合视图并添加第二部分来管理详细信息视图会更简单吗?
答案 2 :(得分:0)
我在集合视图中遇到了相同的问题。经过一番尝试,我意识到解决此问题的概念是找出那些视图的控制器,无论它们是表视图还是集合视图,然后使用该控制器导航到新的控制器。
声明一个控制器变量,以后可以在表视图中访问它。 var controller = ViewController()
(按照我的风格,我更喜欢将其写为全局变量)
将声明的控制器变量分配给self,以使引用指向该变量。
class ViewController: UIViewController{
override func loadView() {
controller = self
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
controller.navigationController?.pushViewController(DetailViewController(), animated: true)
}