2017-10-07 34 views
0

我已经把一个uicollectionview放入了一个uitableview。在选择表视图单元格内的collectionview单元格后,我遇到了另一个viewcontroller的麻烦。从uicollectionview中查看是在桌面视图内

// if the user selects a cell, navigate to the viewcontroller 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    // we check did cell exists or did we pressed a cell 
    if let cell = sender as? UICollectionViewCell { 

     let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell") as! TestingTableView 

     // define index to later on pass exact guest user related info 
     let index = cell2.collectionView?.indexPath(for: cell)!.row 

     print(index as Any) 

     // if segue is guest... 
     if segue.identifier == "guest" { 

      // call guestvc to access guest var 
      let guestvc = segue.destination as! GuestCommunityViewVC 

      // assign guest user inf to guest var 
      guestvc.guest = communities[index!] as! NSDictionary 


     } 

    } 

} 

} 

我在该行收到一个错误:

let index = cell2.collectionView?.indexPath(for: cell)!.row 

,因为跟它的价值为零。有没有人知道一个更好的方法来做到这一点?

+0

在上面的错误提示行中,您将出现一个单元格并将其转换为TestingTableView对象。你的意思是把这个当作一个TableViewCell吗? – bjd23

+0

@ bjd23我的集合视图插座是在表视图单元类中声明的,因为它嵌套在表视图中。这是我可以访问collectionview的索引路径的唯一方法。但是,如果它返回nil,我认为它甚至不会获得collectionview的indexpath。我一直在为此奋斗一段时间。有什么建议么? – ILoveToCode22

+0

为什么不使用委托,所以当按下UICollectionViewCell时,它会将此内容发送给UITableView所在的ViewController? – Jay

回答

1

下面是如何使用委托的示例:

1)的一类声明之外创建一个协议:

protocol customProtocolName:class { 
     func pushToNewView(withData:[DataType]) 
} 

注:为了防止一个参考周期使用类

2)创建保持该参考UICollectionView所述的UITableViewCell内部的代表:

class customUITableViewCell { 
     weak var delegate:customProtocolName? = nil 
} 

3),它保存参考的UITableView的UIViewController的内部,确保你补充协议,除了类的声明,并添加我们创建,以确保协议规范满意的功能:

class customViewController: customProtocolName { 
    func pushToNewView(withData:[DataType]) { 
     //inside here is where you will write the code to trigger the segue to the desired new UIViewController 
     //You can take this new data and store it in this ViewController and then during the segue pass it along 
    } 
} 

4)的的UITableViewDelegate功能,“cellForRowAt”,设置委托customUITableViewCell内部自我:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customUITableViewCell 
     cell.delegate = self 
    return cell 
} 

5)customUITableViewCell,其中UICollectionView委托函数处理内部“didSelectItemAt”委托功能,触发协议功能有像这样:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    delegate?.pushToNewView(withData:[DataType]) 
} 

这是一个非常简单的例子,如果你想传递一个IndexPath,那么你可以修改函数来进行。你也可以传回任何你想要的东西,它不受限制。

+0

但我如何将一个在tableViewCell类中的数组与segue转移到下一个viewController –

+1

我修改了我的答案以显示如何使用委托来传递数据,然后在segue委托函数期间,您可以将信息传递给下一个viewController。尝试忽略命名约定,这是一个非常简单的例子,您需要为您修改项目。另外“DataType”是可以互换的自定义数据对象类型,如果您创建了一个,那么您将使用该类型。 – Jay