我有一个包含多个单元格的集合视图。当用户单击该单元格时,它将选择另一个视图控制器。如何将用户单击的那个单元格的图像插入新的视图控制器?
我已经在主视图控制器中尝试过此操作:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = storyboard?.instantiateInitialViewController(withIdentifier: "FoodDetailViewController") as? FoodDetailViewController
self.navigationController?.pushViewController(vc!, animated: true )
}
这是Detail segue的代码:
class FoodDetailViewController: UIViewController {
var recipe: Recipe!
var text: String!
var body: String!
@IBOutlet weak var foodImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
title = recipe.name
}
private lazy var imageView: UIImageView = {
let view = UIImageView()
view.image = UIImage(named: "PP grey")
return view
}()
var image: UIImage? {
didSet {
imageView.image = image
}
}
答案 0 :(得分:0)
您可以尝试
let vc = storyboard!.instantiateInitialViewController(withIdentifier: "FoodDetailViewController") as! FoodDetailViewController
vc.recipe = recipes[indexPath.item] // assign property here
self.navigationController?.pushViewController(vc!, animated: true)
注意:使用pushViewController与segues无关,如果要使用segue,则重写prepeareForReuse方法并将数据设置为目标vc
答案 1 :(得分:0)
在collectioView didSelectItemAt
方法中,您只需要获取SELECTED单元格,然后从该单元格中获取图像,然后简单地将其传递给NEXT ViewController。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = self.collectionView.cellForRowAtIndexPath(indexPath)
let cell-image = cell?.IMAGEVIEW.image
let vc = storyboard?.instantiateInitialViewController(withIdentifier: "FoodDetailViewController") as? FoodDetailViewController
vc.image = cell-image
self.navigationController?.pushViewController(vc!, animated: true )
}
class FoodDetailViewController: UIViewController {
var image: UIImage?
}
答案 2 :(得分:0)
您可以做的是在情节提要中添加一个segue并覆盖功能prepare(for segue:, sender:)
,在其中您需要使用所需的食谱来设置FoodDetails。做类似的事情:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// you need to identify your segue in the storyboard
if segue.identifier == "GoToFoodDetails" {
if let viewController = segue.destination as? FoodDetailViewController {
viewController.recipe = selectedRecipe
}
}
}
对于所选食谱,您可以使用didSelectItemAt
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedRecipe = recipes[indexPath.row]
performSegue(withIdentifier: "GoToFoodDetails", sender: self)
}