Search code examples
swiftuiimagedelay

In Swift, how can I change the image on a button and change it back after the user has seen the original (ie. flipping a card over)?


sender.setBackgroundImage(imageArray[index], forState: .Normal)

sleep(2)         // wait before you flip back over

sender.setBackgroundImage(cardBack, forState: .Normal)

The sleep seems to stop the image from completing its load. How can I wait for the setBackgroundImage to complete?


Solution

  • sender.setBackgroundImage(imageArray[index], forState: .Normal)
    sender.enabled = false;
    
    let delay_time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 2 * Int64(NSEC_PER_SEC))
    dispatch_after(delay_time, dispatch_get_main_queue()) {
        sender.setBackgroundImage(cardBack, forState: .Normal)
        sender.enabled = true;
    }
    

    Edit: Disable the button while it is showing the image.