skip to Main Content

As asked on the question. On my first VC, I have set up a function that passes an image to another VC as follows.

 @objc func imageTapped(tapGestureRecognizer1: UITapGestureRecognizer) {
        let passimage = tapGestureRecognizer1.view as! UIImageView
        let alertController = UIAlertController(title: "...", message: "...", preferredStyle: UIAlertController.Style.alert)
        let ok = UIAlertAction(title: "...", style: UIAlertAction.Style.default, handler: {(action) -> Void in
            self.performSegue(withIdentifier: "Shop", sender: self)
            print("image tapped")
            
            let sb = self.storyboard?.instantiateViewController(withIdentifier: "shopVC") as! shopVC
            sb.loadimage = passimage.image
            self.present(sb, animated: true, completion: nil)
        })
        alertController.addAction(ok)
        alertController.addAction(UIAlertAction(title: "取消(留在此版面)", style: UIAlertAction.Style.cancel, handler: nil))
        self.present(alertController, animated: true, completion: nil)
    }

whilst on the other VC, I’ve set up an Image View which would read the image as shown here.

class shopVC: UIViewController {
    @IBOutlet weak var clothimage: UIImageView!
 var loadimage: UIImage?
    
    override func viewDidLoad() {
        
        clothimage.image = loadimage
        
        super.viewDidLoad()
        
    }

I know the "passimage.image" is what I want as it shows up in the debugging window – I can’t seem to place it in the second VC.

2

Answers


  1. Need to call super.viewDidLoad() first and then setting up clothimage

    Login or Signup to reply.
  2. for change ViewController you use two Option same Time, When used individually, each:

    // optionOne
        self.performSegue(withIdentifier: "Shop", sender: self)
                    print("image tapped")
    
    // optionTwo                
                    let sb = self.storyboard?.instantiateViewController(withIdentifier: "shopVC") as! shopVC
                    sb.loadimage = passimage.image
                    self.present(sb, animated: true, completion: nil)
    

    if use Option One, you must override below function from firstVC and set image directly:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let vc = segue.destination as? shopVC {
                vc.image = yourImage
            }
        }
    

    and if you use present for show ShopVC nothing change code just comment performSegue function.
    That means only the following code:

    let sb = self.storyboard?.instantiateViewController(withIdentifier: "shopVC") as! shopVC
                        sb.loadimage = passimage.image
                        self.present(sb, animated: true, completion: nil)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search