[英]Navigate to view controller from Tableview cell inside collectionview
所以我在collectionview中嵌入了tableview。 我有桌面视图的xib。 当用户选择tableview的单元格时,我想导航到另一个视图控制器。
我试过这种方法,但它不起作用
let storyboardId = "Login"
let vc = storyboard?.instantiateViewController(withIdentifier: storyboardId)
navigationController?.pushViewController(vc!, animated: true)
但它没有工作,因为这个viewcontroller没有添加到导航堆栈。
class DetailCollectionViewCell: UICollectionViewCell, UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let navigationController = UINavigationController()
// let storyboardId = "Login"
// let vc = storyboard?.instantiateViewController(withIdentifier: storyboardId)
// navigationController?.pushViewController(vc!, animated: true)
}
}
我该如何解决这个问题。 任何帮助表示赞赏。
您有以下选择
1)在viewController中实现tableview数据源和delgate,而不是集合视图单元
2)使用代表(解释如下)
3)使用闭包
4)使用NotificationCenter
您需要创建委托或协议,因为集合视图单元格无法推送或呈现视图控制器。
这是一个简单的例子(这不是你可能需要修改的确切代码)
创建协议
protocol TableViewInsideCollectionViewDelegate:class {
func cellTaped(data:IndexPath)
}
在您的collectionview单元格中添加弱属性
weak var delegate:TableViewInsideCollectionViewDelegate?
现在,在ViewController类中,您需要将delegate设置为self,而不是集合视图的cellForItem方法
喜欢
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCell", for: indexPath) as! CustomCollectionCell
cell.delegate = self
return cell
并在viewController类中实现委托方法并编写代码以从那里推送视图控制器,如self.navigationController.push
现在在Goto Collectionview Cell方法中
每当你的tableviewDidSelect被调用时
调用委托方法,如self.delegate?.cellTaped(data: dataYouWantToPass)
希望它有所帮助
代码示例:
第1步:创建协议。
protocol RowSelected : class { func rowSelected(_ index : Int) }
第2步:在TableViewCell中声明委托变量。
weak var delegate: RowSelected?
第3步:在集合视图中确认委托和实现委托方法。
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath) as! CollectionViewCell cell.delegate = self return cell extension CollectionViewCell : RowSelected { func rowSelected() { // Pass the information to view controller via a delegate/closure/notification. just like we passed information from table view cell to collection view cell and handle navigation accordingly. } }
第4步:在ViewController中,您可以确认集合视图的委托并实现它的委托方法并可以处理导航。
您还可以使用闭包和通知中心通知视图控制器导航到下一个屏幕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.