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

问题描述 投票:-1回答:1

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

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

家庭视图控制器

    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

    }

}
ios swift uicollectionview
1个回答
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)
}
© www.soinside.com 2019 - 2024. All rights reserved.