Skip to content

Instantly share code, notes, and snippets.

@kboy-silvergym
Last active May 25, 2020 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kboy-silvergym/62de6540ee61d879ca584e707719e171 to your computer and use it in GitHub Desktop.
Save kboy-silvergym/62de6540ee61d879ca584e707719e171 to your computer and use it in GitHub Desktop.
Micro Interact UIButton

This UIButton changes own size like Snapchat buttons.

It will turn bigger during forcusing, and will turn default size when you release.

gif -8beb70b6fec0-1 gif -f5cc3a238cb3-1
import UIKit

class MicroInteractButton: UIButton {
    private var clickListener: (() -> Void)?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupAnimation()
        adjustsImageWhenHighlighted = false
    }
    
    func setOnClickListener(_ completion: (() -> Void)?) {
        clickListener = completion
    }
    
    private func setupAnimation(){
        addTarget(self, action: #selector(pressed), for: [.touchDown])
        addTarget(self, action: #selector(released), for: [.touchUpInside, .touchUpOutside, .touchCancel])
    }
    
    @objc private func pressed(){
        expandAnimation()
    }
    
    @objc private func released(){
        shrinkAnimation()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.clickListener?()
        }
    }
    
    private func expandAnimation() {
        let expand = CASpringAnimation(keyPath: "transform.scale")
        expand.duration = 0.2
        expand.fromValue = 1
        expand.toValue = 1.3
        expand.autoreverses = false
        expand.repeatCount = 1
        expand.initialVelocity = 0.8
        expand.damping = 1.0
        expand.fillMode = kCAFillModeForwards
        expand.isRemovedOnCompletion = false
        layer.bounds = self.bounds
        layer.contentsGravity = "center"
        layer.add(expand, forKey: "expand")
    }
    
    private func shrinkAnimation() {
        let shrink = CABasicAnimation(keyPath: "transform.scale")
        shrink.duration = 0.2
        shrink.fromValue = 1.3
        shrink.toValue = 1
        shrink.autoreverses = false
        shrink.repeatCount = 1
        shrink.fillMode = kCAFillModeForwards
        shrink.isRemovedOnCompletion = false
        layer.add(shrink, forKey: "shrink")
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment