0

UIButton在故事板上有一首单曲。与动作UIButton有关。当用户从内部 ( ) 拖动按钮时触发该操作。Touch Drag InsidemyTouchDragInsideActionUIControlEventTouchDragInside

问题是该动作是在内部拖动 1 个像素后触发的。但是 1 像素太敏感了,只需轻轻一点手指即可触发。

@IBAction func myTouchDragInsideAction(sender: UIButton) {

    print("Button dragged inside")

}

问题:

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

4

2 回答 2

2

您必须为其创建自定义按钮。关注 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
    }
}

您根据您的要求更改“延迟点”。希望这会帮助你。

于 2016-04-27T11:05:23.767 回答
0

我对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
    }
}
于 2016-08-01T18:03:59.480 回答