Skip to content

Instantly share code, notes, and snippets.

@douglashill
Created April 27, 2017 08:49
Show Gist options
  • Select an option

  • Save douglashill/c3c184769b4e71dcc9e8c0b8f0a0898c to your computer and use it in GitHub Desktop.

Select an option

Save douglashill/c3c184769b4e71dcc9e8c0b8f0a0898c to your computer and use it in GitHub Desktop.
(Not working well yet) What if a button had a variable touch down state without using a canned animation?
import UIKit
class LiveSquishButton: UIView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
updateSquish(with: 0.05)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
updateSquish(with: touches)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
updateSquish(with: 0)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
updateSquish(with: 0)
}
private func updateSquish(with touches: Set<UITouch>) {
guard let touch = touches.first else {
return
}
let force: CGFloat
if traitCollection.forceTouchCapability == .available, touch.force > 0 {
force = touch.force
} else {
force = 1 // this occurs both when the touch moves (in which case we should not update the scale) and when using the mouse (in which case we should use a force of 1)
}
updateSquish(with: force + 0.05)
}
private func updateSquish(with force: CGFloat) {
let scale = 1 - 0.01 * force
transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let button = LiveSquishButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
button.backgroundColor = .red
button.layer.cornerRadius = 20
let container = UIView()
container.backgroundColor = .lightGray
container.addSubview(button)
let vc = UIViewController()
vc.view = container
let window = UIWindow()
self.window = window
window.rootViewController = vc
window.makeKeyAndVisible()
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment