UISegmentedControl отменить выбор / сброс после исчезновения представления - PullRequest
0 голосов
/ 27 декабря 2018

Я пытаюсь исправить небольшую ошибку.У меня есть UISegmentedControl, который продолжает отображать взаимодействие с пользователем, если я возвращаюсь назад, нажимая на сегмент (не отпуская палец, который выбирает сегмент на экране): enter image description here

Iпопытался отменить выбор сегмента на viewWillDisappear, но я ничего не изменил.Любые идеи о том, как сбросить состояние UISegmentedControl?

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

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

1 Ответ

0 голосов
/ 27 декабря 2018

Проблема в том, что в этом конкретном случае (оставляя экран при прикосновении к элементу управления) функции 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
}
...