Search code examples
iosiphonexcodeswift2ios9

How to stop ios button from functioning until a particular condition is met?


I have a save image button which is used to save an image to the photo library after a new image is taken, or an existing photo is imported and modified inside the app.

However, if the save image button is pressed without an image taken or loaded into the app, it hangs and becomes unresponsive due to it not being able to save an image.

Any advice on what I would need to stop the button from functioning until an image is loaded?

//Save Image Button Function
@IBAction func saveImage(_ sender: AnyObject) {
    let imageData = UIImageJPEGRepresentation(photoViewer.image!, 1.0)
    let compressedJPGImage = UIImage(data: imageData!)
    UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)
    let alert = UIAlertView(title: "Saved!",
                            message: "Your image has been saved to Photo Library!",
                            delegate: nil,
                            cancelButtonTitle: "Ok")
    alert.show()

Solution

  • First, in viewDidLoad, disable the button from being pressed by:

    button.enabled = false
    

    Then, use a conditional if statement where it is checked whether an image has been loaded into the app. If it has, re enable the button by:

    button.enabled = true