在 5 个像素而不是默认的 1 个像素后触摸拖动到 UIButton 内

Touch Drag Inside a UIButton after 5 pixels instead of default 1 pixel

我在故事板上有一个 UIButtonUIButton 连接到 Touch Drag Inside 操作 myTouchDragInsideAction。当用户从内部拖动按钮时触发该操作 (UIControlEventTouchDragInside)。

问题是在内部拖动 1 个像素后触发动作。不过1像素太灵敏了,手指轻轻一动就能触发。

@IBAction func myTouchDragInsideAction(sender: UIButton) {

    print("Button dragged inside")

}

问题:

如何扩展此动作以在移动至少 5 个像素后仅触发内部拖动动作?

您必须为其创建自定义按钮。关注 CustomButton 可能会对您有所帮助。

let DelayPoint:CGFloat = 5

class CustomButton: UIButton {

    var startPoint:CGPoint?

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        if self.startPoint == nil {
          self.startPoint = touches.first?.previousLocationInView(self)
        }


        if self.shouldAllowForSendActionForPoint((touches.first?.locationInView(self))!) {
            super.touchesMoved(touches, withEvent: event)
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.startPoint = nil
        super.touchesEnded(touches, withEvent: event)
    }

    func shouldAllowForSendActionForPoint(location:CGPoint) -> Bool {

        if self.startPoint != nil {

            let xDiff = (self.startPoint?.x)! - location.x
            let yDiff = (self.startPoint?.y)! - location.y

            if (xDiff > DelayPoint || xDiff < -DelayPoint || yDiff > DelayPoint || yDiff < -DelayPoint) {

                return true
            }
        }
        return false
    }
}

您可以根据您的要求更改 "DelayPoint"。 希望对您有所帮助。

我为 Swift 3

实施
final class DraggedButton: UIButton {

    // MARK: - Public Properties
    @IBInspectable var sensitivityOfDrag: CGFloat = 5

    // MARK: - Private Properties
    private var startDragPoint: CGPoint?

    // MARK: - UIResponder
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let firstTouch = touches.first else {
            return
        }

        let location = firstTouch.location(in: self)
        let previousLocation = firstTouch.previousLocation(in: self)

        if startDragPoint == nil {
            startDragPoint = previousLocation
        }

        if shouldAllowForSendActionForPoint(location: location) {
            super.touchesMoved(touches, with: event)
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        startDragPoint = nil
        super.touchesEnded(touches, with: event)
    }

    // MARK: - Private methods
    private func shouldAllowForSendActionForPoint(location: CGPoint) -> Bool {
        guard let startDragPoint = startDragPoint else {
            return false
        }

        let xDifferent = abs(startDragPoint.x - location.x)
        let yDifferent = abs(startDragPoint.y - location.y)
        return xDifferent > sensitivityOfDrag || yDifferent > sensitivityOfDrag
    }
}