Search code examples
iosswiftxcodeswift-playgroundswift4.2

If Button clicked - do animation to image Swift Playgrounds


My goal is simple. When a button is clicked, the button should fade out and so should another image on the screen. I am using Swift Playgrounds. I have already got the button to fade out when clicked working. The main problem is getting the image on the screen to fade out once the button is clicked.

import PlaygroundSupport
import AVFoundation
class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let title = UIImage(named: "Picture1")
        let imageView = UIImageView(image: title) //this is the image I want to fade out when the button is clicked
        imageView.image = title
        imageView.frame.size.width = 570
        imageView.frame.size.height = 140
        imageView.frame.origin.x = 100
        imageView.frame.origin.y = 0
        imageView.alpha = 0

        let button = UIButton(type: UIButton.ButtonType.custom) as UIButton
        let image = UIImage(named: "startbutton4.png") as UIImage?
        button.frame = CGRect(x: 265, y: 300, width: 249, height: 85)
        button.setImage(image, for: [])
        button.contentMode = .center
        button.imageView?.contentMode = .scaleAspectFit


        button.imageView?.contentMode = .scaleAspectFit
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        self.view.addSubview(button)
        view.addSubview(imageView)
    }

    @objc func buttonAction(sender: UIButton) {
        sender.isHighlighted = false
        UIView.animate(withDuration: 1, delay: 1, options: .curveEaseOut, animations: {
           sender.alpha = 0
        }, completion: nil) // <--- this right here is the button fading out 
    }

}
let master = MyViewController()
PlaygroundPage.current.liveView = master

If anyone has any idea how to do this, please let me know.


Solution

  • What i understand is you want to hide button ... once button is hidden you want to show image .. here is the code for that.. i hope it will help

    func buttonAction(sender: UIButton) {
        sender.isHighlighted = false
        UIView.animate(withDuration: 1, delay: 1, options: .curveEaseOut, animations: {
           sender.alpha = 0
        }, completion: { success in
            if success {
            UIView.animate(withDuration: 1, delay: 1, options: .curveEaseOut, animations: {
               imageView.alpha = 1
                })
            }
        })
    }