简体   繁体   中英

How do I pass an image view and its properties from one view controller to another?

So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images


//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).

First you have to store the background image index that you will set in func randomImage() . So you have to declare a class variable

class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!
let randomIndex:Int!
let backgroundImages = //array containing all the images


//random image generator function 
func randomImage() {
    // So now you can pass this value to next viewController.
    randomIndex = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[randomIndex]

}

您可以使用情节提要segue并与prepare语句共享图像,否则可以创建第二个vc的实例,然后需要初始化一个图像视图,而不是需要从第一个VC设置该图像视图并推送该vc。

制作UIImageView的子类并使用它。

You can save the image as a png in the user document folder and reload it as needed. See my recent answer to an unrelated question:

Saving an image to User Documents folder

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