繁体   English   中英

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

[英]Swift 4: Passing data from a collection view cell into another view controller without storyboards

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

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

主视图控制器

    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

    }

}

为 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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM