UISegmentedControl 在视图消失后取消选择/重置

UISegmentedControl deselect / reset after view disappears

我正在尝试修复一个小错误。我有一个 UISegmentedControl,如果我在按下一个片段的同时导航回来(不松开从屏幕上选择片段的手指),它会一直显示用户交互:

我试图取消选择 viewWillDisappear 上的细分市场,但没有任何效果。关于如何重置 UISegmentedControl 的状态有什么想法吗?

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    fixedPositionSegmentControl.selectedSegmentIndex = UISegmentedControl.noSegment
    fixedPositionSegmentControl.selectedSegmentIndex = 0
}

问题是在这种特定情况下(触摸控件时离开屏幕)分段控件的 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
}