Skip to content

Instantly share code, notes, and snippets.

@smosko
Created July 17, 2019 09:57
Show Gist options
  • Save smosko/b74842746c96bc4d85d75abbd6c63599 to your computer and use it in GitHub Desktop.
Save smosko/b74842746c96bc4d85d75abbd6c63599 to your computer and use it in GitHub Desktop.
import UIKit
import PlaygroundSupport
class AnimatedButton: UIButton {
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
var highlightAnimation = false
override var isHighlighted: Bool {
didSet {
guard highlightAnimation else { return }
let transform: CGAffineTransform = isHighlighted ? .init(scaleX: 0.95, y: 0.95) : .identity
UIView.animate(
withDuration: 0.4,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 3,
options: [.curveEaseInOut],
animations: { self.transform = transform }
)
}
}
}
class MyViewController : UIViewController {
lazy var button: UIButton = {
let button = AnimatedButton()
button.setTitle("Subscribe", for: .normal)
button.backgroundColor = .red
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 40, bottom: 10, right: 40)
button.cornerRadius = 10
button.highlightAnimation = true
return button
}()
override func loadView() {
view = UIView()
view.backgroundColor = .white
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
}
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment