create a grey button with the text "press here" which jumps when you press it in swift

Here's an example of how to create a grey button with the text "press here" which jumps when you press it in Swift:

  1. Create a new UIButton instance, and set its frame and text properties:
main.swift
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
button.setTitle("press here", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = UIColor.darkGray
button.layer.cornerRadius = 5.0
234 chars
6 lines
  1. Add a touch up inside event to the button, and create a UIView.animate block to animate the button's position:
main.swift
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

@objc func buttonPressed() {
    UIView.animate(withDuration: 0.1, delay: 0, options: [.autoreverse], animations: {
        self.button.transform = CGAffineTransform(translationX: 0, y: -10)
    }, completion: nil)
}
296 chars
8 lines

This will make the button jump 10 points (∼15 pixels) upward and downward when pressed. You can adjust these values to your liking.

Also, don't forget to add the button to your view controller's view:

main.swift
view.addSubview(button)
24 chars
2 lines

related categories

gistlibby LogSnag