简体   繁体   中英

How do i access/pass variable from another view controller? It's not the next view controller, but the view controller after the next one in Swift

The arrangement of segue of view controller is like this:

TakeAPicVC -> PickALanguageVC -> Play AudioVC

I want to display a picture from TakeAPicVC in PlayAudioVC

You can use delegate and closure. If you never used, here you need.

// define delegate for PassPicture 
protocol PassPictureDelegate { 
  func getPicture() -> UIImage
}

// or you can use closure
typealias PassImageClosure = ((UIImage) -> Void)

class TakeAPicVC: UIViewController { 

  override func viewDidLoad() { 
    super.viewDidLoad()

    // when present next vc
    let picLanguageVC = PicALanguageVC()
    picLanguageVC.delegate = self

    /* use closure 
    picLanguageVC.passImageClosure?(you_pass_image_here)
    */
  }
}

extension TakeAPicVC: PassPictureDelegate { 
  func getPicture() -> UIImage { 
    return image // pass the picture here.
  }
}

class PickALanguageVC: UIViewController { 
  weak var delegate: PassPictureDelegate?

  // use closure.
  // -> var passImageClosure: PassImageClosure?

  // your playAudioVC
  var playAudioVC: PlayAudioVC!

  override func viewDidLoad() { 
    super.viewDidLoad()
    // when you initialize about this vc.
    playAudioVC = PlayAudioViewController()
    playAudioVC.delegate = delegate    

    /* use closure
    playAudioVC.passImageClosure = self.passImageClosure
    */ 
  }
}

class PlayAudioVC: UIViewController { 
  weak var delegate: PassPictureDelegate?
  // 2) closure 
  var passImageClosure: PassImageClosure?

  @IBOutlet weak var yourImageView: UIImageView!

  override func viewDidLoad() { 
    super.viewDidLoad()
    yourImageView.image = delegate?.getImage()

    /* use closure
    passImageClosure = { [weak self] image in 
      DispatchQueue.main.async { 
        self?.yourImageView.image = image
      }
    }
    */
  }
}

As a quick and easy solution you could pass the image reference to the first ViewController and from there to the second one. So both ViewControllers, PickALanguageVC and PlayAudioVC , would hold the image reference.

Maybe not the most elegant solution from an architectural point of view but it could work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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