Home>

I want to take action the moment I touch the Button without removing my finger from the screen. ..
Is there a good way?
I tried to implement it with UIPanGestureRecognizer, but I can take action when I drag and touch it, but what should I do to take action the moment I touch the button other than dragging?

I'm new to swift, so if you have sample code, I'd appreciate it.

  • Answer # 1

    UIControl.EventoftouchDownYou can use.

    I think the following site will be helpful.

    https://hajihaji-lemon.com/swift/uibutton_event/

    StoryboardOrXIBThenUIButtonAt the time of placementEventJust change it in the part.
    I think that the code can be used like the following.

    import UIKit
    class ViewController: UIViewController {
        override func viewDidLoad () {
            super.viewDidLoad ()
            let button = UIButton (type: .system)
            button.setTitle ("Button", for: .normal)
            button.frame = CGRect (x: 10, y: 100, width: 100, height: 44)
            button.addTarget (self,
                             action: #selector (buttonTapped),
                             for: .touchDown) // Usually touchUpInside
            view.addSubview (button)
        }
        @objc func buttonTapped () {
            print ("Button tapped")
        }
    }