The best way to perform actions on 3D Touch on UIButton

I have the number of instances UIButtonin UIViewController, and I want to perform a couple of actions, when any of these buttons are pressed with a push (all the way down), I don’t know the exact term here (maybe a touch of force)?

So, when UIButtonpressed, I want to give a hapel feedback via vibration, change the button's image source, and do some other things. Then, when the pressure is released, I want to restore the button image source to its normal state and do a few more things.

What is the easiest way to do this?

Do I have to make my own custom UIButton, as shown below, or are there methods that can be overridden for three-dimensional pressing "press" and "release".

This is my custom UIButton code. Should I determine, through trial and error, what should be the maximum strength? Also, how can I change the image source for each button in the easiest way?

import AudioToolbox
import UIKit

class customButton : UIButton {
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in touches {
            print("% Touch pressure: \(touch.force/touch.maximumPossibleForce)");
            if touch.force > valueThatIMustFindOut {
                AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
                // change image source
                // call external function
            }
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("Touches End")
        // restore image source
        // call external function
    }
}

Note that I am new to Swift, so I would like to use the GUI in Xcode to create the user interface as much as possible. Therefore, I would like to avoid creating a user interface from code.

+4
source share
1 answer

- , :

func is3dTouchAvailable(traitCollection: UITraitCollection) -> Bool {
    return traitCollection.forceTouchCapability == UIForceTouchCapability.available
}

if(is3dTouchAvailable(traitCollection: self.view!.traitCollection)) {
   //...
}

, , touchsMoved touch.force touch.maximumPossibleForce

func touchMoved(touch: UITouch, toPoint pos: CGPoint) {
    let location = touch.location(in: self)
    let node = self.atPoint(location)

    //...
    if is3dTouchEnabled {
        bubble.setPressure(pressurePercent: touch.force / touch.maximumPossibleForce)
    } else {
        // ...
    }
}

: http://www.mikitamanko.com/blog/2017/02/01/swift-how-to-use-3d-touch-introduction/

, " " /taptic , :

let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.prepare()

generator.impactOccurred()

: http://www.mikitamanko.com/blog/2017/01/29/haptic-feedback-with-uifeedbackgenerator/

+2

Source: https://habr.com/ru/post/1662058/


All Articles