![](/img/trans.png)
[英]Passing data from a collection view cell button to another view controller (Swift)
[英]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.