How to change the index of UISegmentControl (slide) dynamically without touching segments in Swift?

58 views Asked by At

I am trying to achieve something that I could not find any source or example of it anywhere. I want to implement motion detection and when the user shakes the phone, I want to change the segment without explicitly touching it. So, for example, when the user shakes the phone in my app, it detects the motion and if selectedSegmentIndex is 0 it should move to index 1, likewise if it is on 1st index, it should move to 0's index. So far, I have implemented the motion detection, but i have no idea how to start an event for UiSegmentControl depending on the motion. Is there anywhere to do so? Even is that possible? Please can anyone help me with that? Any possible ideas and examples would be appreciated.

here i have done so far:

override var canBecomeFirstResponder: Bool {
    get {
        return true
    }
}

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        Vibration.heavy.vibrate()
        switch self.mysegmentControl.selectedSegmentIndex {
        case 0:
            print("0")
        case 1:

            print("1")
        default:
            break
        }
    }
}
1

There are 1 answers

1
Vitaly Potlov On

Try:

if motion == .motionShake {
    switch self.mysegmentControl.selectedSegmentIndex {
    case 0:
        self.mysegmentControl.selectedSegmentIndex = 1
    case 1:
        self.mysegmentControl.selectedSegmentIndex = 0
    default:
        break
    }
    self.mysegmentControl.sendActionsForControlEvents(UIControlEvents.ValueChanged)
}