UIScrollView是iOS中用于显示可滚动内容的视图容器。当用户触摸屏幕并开始滚动时,系统会管理一系列触摸事件(touchesBegan, touchesMoved, touchesEnded, touchesCancelled)。
当UIScrollView检测到滚动手势时,它会取消(touchesCancelled)当前正在处理的触摸事件,以便接管滚动行为。这是UIScrollView的默认行为,目的是防止触摸事件和滚动手势之间的冲突。
class CustomScrollView: UIScrollView {
override func touchesShouldCancel(in view: UIView) -> Bool {
if view is UIButton { // 如果是特定视图(如按钮)
return false // 不取消触摸事件
}
return super.touchesShouldCancel(in: view)
}
}
class NonCancellingScrollView: UIScrollView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// 防止滚动时取消触摸
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
// 空实现,不调用super
}
}
class ViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.panGestureRecognizer.delegate = self
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
scrollView.delaysContentTouches = false
以上方法可以根据具体需求选择使用,通常推荐第一种或第三种方案,因为它们提供了更精细的控制而不会完全破坏UIScrollView的默认行为。
没有搜到相关的文章