0

How to show different images in same next viewcontroller when button is pressed.

When first button is pressed it should show one image and when second button is pressed it should show other image in second view controller.

It can be done by use three different view controller and using segue just avoid adding many view controller I want it do display in same view controller.

Thanks in advance.

4
  • Would it not be better to use a UIPagingController? Commented May 11, 2017 at 15:11
  • I think no because when first button is pressed it shows one image and we go back to first view and when second button is pressed it should go to same second view but should show different image. Commented May 11, 2017 at 15:17
  • Why do you need a new ViewController for that? Just change the image of the UIImageView in the same ViewController. Commented May 11, 2017 at 15:19
  • Exactly but how 😁😁 Commented May 11, 2017 at 15:21

2 Answers 2

2

From the original view controller, on prepare, set the name of the image that should be displayed on the next view controller.

On the next view controller you just read that and name and create a UIImage from it.

Origin VC:

var imageToLoad : String = "" @IBAction func btnA(_ sender: UIButton) { imageToLoad = "imageA" } @IBAction func btnB(_ sender: UIButton) { imageToLoad = "imageB" } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destinarionVC = segue.destination as! NEXT_VIEW_CONTROLLER { destinarionVC.imageName = self.imageToLoad } } 

Next VC:

var imageName : String = "" var image : UIImage override func viewDidLoad() { //Or wherever you need it to be image = UIImage(name: imageName) } 
Sign up to request clarification or add additional context in comments.

8 Comments

Done it... Just be sure to use the image wherever you need on the next VC, not necessarily on viewDidLoad
in the second line after prepare it gives erroe : initilaizer for conditional binding must be optional. In Second View I have UIImageview instead of uiimage. I used perform segeue with indentifier to go to next view when button is clicked.
Change ! For ? For The error you got. If you have a UIImageView just initialization that with the image I wrote the code for...
It Worked. Its hard to be newbie. Thanks
when you press the image it goes to third view and when I come back from third view to second view now image does not display. Do I have to do same things as in first view to load the image or is there any simple solutions?
|
0

Try using Carbonkit Framwork

https://github.com/ermalkaleci/CarbonKit

You can use a single view controller and change animation and it feels like its moving to another viewcontroller. Actually its moving to another view controller but it is same view controller as before.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.