简体   繁体   中英

Get Force of long Touch on UIButton

In my app I have a button that is controlled by the amount of force applied, but I can't seem to reliably get updates for the force value.

Right now, I am only registering touches through touchesBegan, touchesMoved, and touchesEnded, which works most of the time but not always.

It is possible to place your finger on the screen and apply pressure without triggering a touchesMoved event. If you press the screen hard (enough to max out the force value) and don't move your finger around, it only calls touchesBegan with the initial (~0) force and doesn't call touchesMoved until you wiggle your finger or release pressure so the force can change from max.

This means there is no way of telling that the user is currently pressing down hard. Does anyone know of a way to constantly poll for touches and read their force value? Is there some other way of reading touchscreen information besides the touch events?

This function purely relies on force touching, so I don't care about compatibility for users without 3D Touch, have it turned off, or accessibility accommodations. Thanks!

EDIT: I seem to have misidentified the problem. The touchesBegan (and beginTracking) events are not called when pressing down hard without moving until ~1 second after the press. When they are, the max force is shown (meaning the current, not beginning value) I have tested that this is true in other apps and it takes some practice to get right. Could this be the system anticipating some peek behavior and withholding the touch? Is there any way around it?

Do not use touchesBegan method with UIButton subclass. Instead of this simply override these two methods..

class Button: UIButton {
    override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        //This is the alternate method of touchesBegan
        return true
    }
    override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        //This is the alternate method of touchesMoved
        let force = touch.force
        return true
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM