Home > OS >  Can I pass data to two different pages by didSelectItemAt I tried like this and did not succeed
Can I pass data to two different pages by didSelectItemAt I tried like this and did not succeed

Time:12-24

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       let data = detlCafe[indexPath.row]

       let nextVC = ShowCafe()
       let placeLoc = PleacOnMap()
       
       nextVC.cafeImg1.image = UIImage(named: data.img1)
       nextVC.cafeImg2.image = UIImage(named: data.img2)
       nextVC.nameCafe.text = data.nameCafe
       nextVC.detlCafe.text = data.descCafe
       
       placeLoc.lat = data.latitude
       placeLoc.long = data.longitude
       
       present(placeLoc, animated: true, completion: nil)
       present(nextVC, animated: true, completion: nil)
   }

CodePudding user response:

It's possible to pass data to two different view controllers.

What's not possible is to present two different view controllers modally like you are doing. It also doesn't really make sense in terms of the user experience. You need to decide what the user experience will be, and then figure out how to implement that.

If you need to send data to 2 different screens that are already displayed (in a tab controller, page view controller, or navigation stack, for example) you could hold pointers to to those view controllers and update them with new information. However, it doesn't really make sense in iOS to create 2 new view controllers in response to a user action.

Also, how are the views in your ShowCafe() and PleacOnMap() view controllers defined? If they are defined in a Storyboard then calling init on them won't work. You will need to load them from their storyboard using the Storyboard instantiateViewController(withIdentifier:) method.

CodePudding user response:

You can pass data from one view to another view by doing this:

This is the view controller that you want to go to next:

class NewViewController: UIViewController {

init(passInString: String, passData: Data) {
    super.init(nibName: nil, bundle: nil)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

just pass in whatever data you want into the init() and you will be able to pass data from one view controller to the next.

Here is the didSelectItemAt function which you can now use to pass in a string and data (or anything else) into the NewViewController:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let string = "This is my string"
    let Data = Data()
    let vc = NewViewController(passInString: string, passData: Data)
    present(vc, animated: true)
}

You have now passed in a string and data into your new view controller.

  • Related