我正在使用 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 容器中,当我将拇指 View 拖动一小段距离时,触摸会以某种方式被取消这可能是 View 容器的问题,我该如何解决?
感谢您阅读全文。
最佳答案
当我的自定义 UIControl 在表单上时,我最近遇到了这个问题。它在弹出窗口上运行良好,但是当我将相同的控件放在表单上时,它会突然中止横向拖动的能力,似乎没有任何理由。 cancelTracking
被调用,但事件没有告诉我原因。我发现这与 iOS13 通过向下拖动来解除 Formsheets 的新方法有关。为了修复它,我将此代码添加到扩展 UIControl 的类中:
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UIPanGestureRecognizer {
return false
}
return true
}
关于ios - 拖入自定义分段控件时意外调用cancelTracking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45779645/