所以我有2个视图控制器,左边显示的是1个嵌入式集合视图,右边显示的那个有2个嵌入式集合视图。
当尝试将数据(packSelected)从一个传递给另一个时,prepareforsegue方法不起作用,因为我希望它更改视图控制器并且信息来自UICollectionViewController类。所以目前我正在使用以下代码来实现' segue'当选择嵌入在左侧viewcontroller中的collectionview的单元格时,来自UICollectionViewController类的2个视图控制器之间:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: PackCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PackCollectionViewCell
//cell.labelCell.text = tableData[indexPath.row]
//cell.imageCell.image = UIImage(named: tableImages[indexPath.row])
cell.labelCell.text = packsDescription[indexPath.row]
cell.imageCell.image = UIImage(named: packsImage[indexPath.row])
cell.imageCell.layer.masksToBounds = true
cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height/2
cell.imageCell.layer.borderWidth = 3
cell.imageCell.layer.borderColor = UIColorFromHEX(hexValue: 0x62aca2).cgColor
return cell
}
var packSelected: String = ""
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(packsName[indexPath.row])
packSelected = packsName[indexPath.row]
//performSegue(withIdentifier: "packView2Journey", sender: self)
transportMe()
}
func transportMe() {
let storyboard: UIStoryboard = UIStoryboard (name: "Main", bundle: nil)
let vc: JourneyViewController = storyboard.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
let currentController = getCurrentViewController()
currentController?.present(vc, animated: false, completion: nil)
}
func getCurrentViewController() -> UIViewController? {
if let rootController = UIApplication.shared.keyWindow?.rootViewController {
var currentController: UIViewController! = rootController
while( currentController.presentedViewController != nil ) {
currentController = currentController.presentedViewController
}
return currentController
}
return nil
}
现在的问题是,我无法将任何数据发送到嵌入在右侧视图控制器中的其他集合视图。
---------------编辑------------------------------- -
用委托方法解决。
class PackCollectionViewController: UICollectionViewController {
weak var delegate: PackCollectionViewDelegate?
//....
}
然后在下面创建委托类:
protocol PackCollectionViewDelegate : class {
func packSelected (_ selector: PackCollectionViewController, didSelect thePackName: String)
}
并在调用transportMe()的函数中,如原始帖子中所示定义要传递的数据:
let passPackName = packsName[indexPath.row] as String
self.delegate?.packSelected(self, didSelect: passPackName)
transportMe()
extension PartCollectionViewController : PackCollectionViewDelegate {
func packSelected (_ selector: PackCollectionViewController, didSelect thePackName: String) {
print(thePackName)
}
}