Swift 4:将数据从集合视图单元传递到另一个没有故事板的视图控制器

时间:2018-03-04 16:39:25

标签: ios swift uicollectionview

所以这可能是一个非常通用的问题,但我不熟悉没有故事板的工作。

我正在尝试将数据从集合视图单元格传递到另一个视图控制器。在新的视图控制器中,我想显示集合视图单元格中显示的数据。

主视图控制器

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return games.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let game = games[indexPath.row]
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? GameCell {

        cell.configureGameCell(game: game)
        return cell
    } else {
        return GameCell()
    }
    return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)

}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  /*I am able to present the view controller but no data is shown*/

    let game = games[indexPath.row]
    let gameDetailsVC = GameDetailsController()
    let navController = UINavigationController(rootViewController: gameDetailsVC)
    present(navController, animated: true, completion: nil)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 130)
}

现在,这是我想要发送数据的视图控制器。设置并不完全相同,但我想表明我想要使用用于填充集合视图单元格的类并使用相同的类信息来填充我的详细信息视图控制器。

详情查看控制器

class GameDetailsController: UIViewController {

var game: Game!
var location: String!
var gameType" String!

override func viewDidLoad() {
    super.viewDidLoad()
    location = game.location
    gameType = game.gameType

    }

}

1 个答案:

答案 0 :(得分:1)

为gameDetailsVC对象的游戏属性赋值

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let game = games[indexPath.row]
    let gameDetailsVC = GameDetailsController()
    gameDetailsVC.game = game
    let navController = UINavigationController(rootViewController: gameDetailsVC)
    present(navController, animated: true, completion: nil)
}