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

时间:2018-12-27 10:02:00

标签: ios swift uisegmentedcontrol

我正在尝试修复一个小错误。我有一个UISegmentedControl,如果我在按下某个段的同时向后导航(不松开要从屏幕上选择该段的手指),它将始终显示用户交互: enter image description here

我尝试取消选择viewWillDisappear上的句段,但没有任何区别。关于如何重置UISegmentedControl的状态的任何想法?

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

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

1 个答案:

答案 0 :(得分:1)

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