Search code examples
iosswiftuibutton3dtouch

Swift 3D Touch Force Value in UIButton


how can I measure the 3D touch force applied to a UIButton function? I want to use it for changing the volume of an AVAudioPlayer property in swift.


Solution

  • You can use something that recognizes 3D touch for all UIView classes \ subclass

    make a custom class

    class customButton : UIButton{
        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            for touch in touches{
                print("% Touch pressure: \(touch.force/touch.maximumPossibleForce)");
            }
        }
    
        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            print("Touches End")
        }
    }
    

    and instead of UIButton Touch Observer (TouchUpInside \ TouchUpInside..) just use this methods above
    this will work for all UIView class

    class customView : UIView ....//same code as above