blaq blaq - 4 months ago 11
Swift Question

Change image when button is pressed and then have image return to original after 5 seconds

So I am new to Swift. I am learning it via video tutorials step by step. However with each tutorial I attempt to make very simple apps to re-enforce what I am learning, and I am moving slowly so I can retain what I am learning.

Down to my question! I have created a very simple app that is no more than a button laid over an image and when the button is pressed the image changes. You then press the reset button and it goes back to the original image. What I want is for the user to press the button then have the image change and 5 seconds later it auto changes back to the original image, "no reset button" for the user to have to press. How can I do this, in a very simple way?

FYI I have several buttons on the screen so I will want to do this for each button individually at this time, as I learn more I will revisit this project and learn to create a single function that I can just call anytime I want to do this, that way creating cleaner code. But I got to walk before I run.

Ok, so here is what my current code looks like. How do I add this into it?

@IBOutlet weak var bkgrdImage: UIImageView!
@IBOutlet weak var yellowDesktopImage: UIImageView!
@IBOutlet weak var greenDesktopImage: UIImageView!
@IBOutlet weak var yellowExpanded: UIImageView!
@IBOutlet weak var greenExpanded: UIImageView!
@IBOutlet weak var yellowButton: UIButton!
@IBOutlet weak var greenButton: UIButton!


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func learnYellow(sender: AnyObject) {
bkgrdImage.hidden = false


yellowDesktopImage.hidden = true
greenDesktopImage.hidden = true
yellowExpanded.hidden = false
greenExpanded.hidden = true
yellowButton.hidden = true
greenButton.hidden = true
}





So where/how do i add this piece of code?

imageView.image = newImage //change to the new image

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
imageView.image = originalImage //change back to the old image after 5 sec
});

Answer

something like this in your button press function should do the job:

Above the class, import Dispatch

imageView.image = newImage //change to the new image

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
    imageView.image = originalImage //change back to the old image after 5 sec
});
Comments