Swift:如何使用Segue选中UICollectionViewCell(在UITableViewCell中)
问题描述:
我想使用segue来显示所选UICollectionViewCell的详细页面,但是这个单元位于UITableViewCell中。问题是我不能在TableViewCell中使用“performSegueWithIdentifier”(一个包含CollectionView),我知道这个函数只能用在UIViewController中,但我的数据(来自JSON)在TableViewCell中。我不知道如何从ViewController访问这些,或者我可以用其他方式来选择TableViewCell中的CollectionViewCell。这里是我的代码:Swift:如何使用Segue选中UICollectionViewCell(在UITableViewCell中)
class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
var posts1: [Posts] = [Posts]()
var posts2: [Posts] = [Posts]()
var categories: [Category] = [Category]()
var selectedPost1: Posts?
我有2门阵列(POST1和posts2),我想SEGUE同时显示在posts1和posts2阵列的所有项目的细节。
我尝试添加功能:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.selectedPost1 = self.posts1[indexPath.row]
}
但我内心不能称之为 “performSegueWithIdentifier”。有关解决这个问题的任何建议?谢谢。
答
你需要在你的UITableViewCell
extension UITableViewCell {
var parentViewController: UITableViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.nextResponder()
if let viewController = parentResponder as? UITableViewController {
return viewController
}
}
return nil
}
}
然后didSelectItemAtIndexPath添加扩展
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
if let tableController = parentViewController as? NameOfYourTableViewController {
tableController.performSegueWithIdentifier(SegueIdentifier, sender: nil)
}
}
我知道如何使用它的时候它是在一个UITableViewController或UIViewController,但我的单元格在另一个单元格中,我怎么能在单元格内调用这个函数? –
你必须有一个主要的UITableViewController,你的单元格正确吗?你从单元格创建一个segue到一个细节视图?我所建议的是你去你的UITableViewController你重写prepareForSegue(不performSegueIdentifier)。像这样的例如 覆盖FUNC prepareForSegue(赛格瑞:UIStoryboardSegue!发信人:AnyObject){ 如果(segue.identifier == “加载视图”){// 数据传递到下一个视图 }} 是 –
,我已经做到了。但我在传递数据时遇到了麻烦。我从互联网上下载了所有数据并将它们存储在一个数组中,并且该数组位于UICollectionView类(它位于TableView内部)中。我怎样才能在主UITableViewController中传递它们?就像我所有的数据存储在“posts1”里面,我怎么能把它们传递给主要的UITableView?谢谢。对不起,我对Swift很陌生。 –