create a button that animates when you tap on it in swift

Here is an example code snippet to create a button animation on tap in Swift using UIKit:

main.swift
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var myButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        myButton.addTarget(self, action: #selector(tapButton), for: .touchUpInside)
    }
    
    @objc func tapButton() {
        
        UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseInOut], animations: {
            
            // set the scale transform
            self.myButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
            
        }, completion: { finished in
            
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseInOut], animations: {
                
                // set the original transform
                self.myButton.transform = CGAffineTransform.identity
                
            }, completion: nil)
        })
    }
}
896 chars
31 lines

First, we add a target and action to the button so that when it's tapped, the tapButton method is triggered.

In the tapButton method, we use the UIView.animate method to animate the button. We set the scale transform of the button and define the animation options (in this example, we're using curveEaseInOut).

Then, we define another animation block to set the original transform of the button when the animation is completed. By using two animations, we add a slight pause in the animation before it returns to the original state, which adds a nice touch to the interaction.

gistlibby LogSnag