问题在于,在这种特定情况下(在触摸控件时离开屏幕)分段控件的 touchesEnded / touchesCancelled 函数不会被调用。所以你可以通过编程方式取消触摸:
override func viewDidDisappear(_ animated: Bool) {
segmentedControl.touchesCancelled(Set<UITouch>(), with: nil)
super.viewDidDisappear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
segmentedControl.selectedSegmentIndex = 0
}
子类化UISegmentedControl 甚至可能是更简洁(但可能过大)的方法:
class SegmentedControl: UISegmentedControl {
// property to store the latest touches
private var touches: Set<UITouch>?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.touches = touches
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
self.touches = touches
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.touches = nil
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
self.touches = nil
}
override func didMoveToWindow() {
// cancel pending touches when the view is removed from the window
if window == nil, let touches = touches {
touchesCancelled(touches, with: nil)
}
}
}
使用这种方法,您可以简单地重置viewWillAppear 中的索引:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
segmentedControl.selectedSegmentIndex = 0
}