在自定义分段控件中拖动时,cancelTracking意外调用

时间:2017-08-20 07:36:08

标签: ios swift cocoa-touch uicontrol segmentedcontrol

我使用this tutorial中的自定义分段控件,此外,我希望在滑动/拖动时更改所选的片段,因此我添加了以下功能:

override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    super.beginTracking(touch, with: event)

    let location = touch.location(in: self)
    lastTouchLocation = location

    return true
}

override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    super.continueTracking(touch, with: event)

    let location = touch.location(in: self)
    print(location.x - lastTouchLocation!.x)

    let newX = thumbView.frame.origin.x + (location.x - lastTouchLocation!.x)
    if frame.minX <= newX && newX + thumbView.frame.width <= frame.maxX {
        thumbView.frame.origin.x = newX
    }
    lastTouchLocation = location

    return true
}

override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
    super.endTracking(touch, with: event)

    let location = touch != nil ? touch!.location(in: self) : lastTouchLocation!

    var calculatedIndex : Int?
    for (index, item) in labels.enumerated() {
        if item.frame.contains(location) {
            calculatedIndex = index
        }
    }

    if calculatedIndex != nil && calculatedIndex != selectedIndex {
        selectedIndex = calculatedIndex!
        sendActions(for: .valueChanged)
    } else {
        displayNewSelectedIndex()
    }
}

我已将控件嵌入到UIView容器中,当我将拇指视图拖动一小段距离时触摸会被取消

enter image description here

这可能是视图容器的问题,我该如何解决这个问题?

如果您已阅读整篇文章,请感谢您。

1 个答案:

答案 0 :(得分:2)

我最近在自定义UIControl放在表单上时遇到了这个问题。它可以在弹出窗口上正常工作,但是当我将相同的控件放在表单上时,它会中止似乎毫无理由地突然侧向拖动的功能。 cancelTracking被叫,但是活动没有告诉我原因。我发现它与iOS13通过向下拖动来关闭Formsheets的新方式有关。为了解决这个问题,我将此代码添加到了扩展UIControl的类中:

override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    if gestureRecognizer is UIPanGestureRecognizer {
        return false
    }
    return true
}