我使用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容器中,当我将拇指视图拖动一小段距离时触摸会被取消
这可能是视图容器的问题,我该如何解决这个问题?
如果您已阅读整篇文章,请感谢您。
答案 0 :(得分:2)
我最近在自定义UIControl放在表单上时遇到了这个问题。它可以在弹出窗口上正常工作,但是当我将相同的控件放在表单上时,它会中止似乎毫无理由地突然侧向拖动的功能。 cancelTracking
被叫,但是活动没有告诉我原因。我发现它与iOS13通过向下拖动来关闭Formsheets的新方式有关。为了解决这个问题,我将此代码添加到了扩展UIControl的类中:
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UIPanGestureRecognizer {
return false
}
return true
}