isMomentary on SegmentedPickerStyle Swiftui

218 Views Asked by At

Trying to set isMomentary of Picker SegmentedPickerStyle in SwiftUI.

UIKit UISegmentedControl has a Bool isMomentary.

Looking for how to achieve the same for SwiftUI

1

There are 1 best solutions below

3
On BEST ANSWER

This is an example of how I handle it. Basically you have your picker set its selection back to whatever default value you want it to be. In this example I have a segmented picker with 5x options from 2 -> 50 miles. I can perform an action after a selection that corresponds to that selection; After which it will return to its default state. You can add a delay or animation to this to make it a bit smoother, but that's outside the scope of this question.

@State var selectedRange = 2
//someView {...

                    Picker(selection: selectedRange, label: Text("Search Radius")) {
                        Text("2 miles").tag(0)
                        Text("5 miles").tag(1)
                        Text("10 miles").tag(2)
                        Text("25 miles").tag(3)
                        Text("50 miles").tag(4)
                    }
                    .pickerStyle(SegmentedPickerStyle())
                    .onChange(of: selectedRange, perform: { value in
                        doAction()
                    })

Function

I actually have mine inside of a ViewModel but in this example it's on the view itself. Just be sure to check scope and put it in the right place.

func doAction() {
    //Do whatever you need to have done.
    switch selectedRange {
        case 0:
            //Do Something.
        default:
            //Do Something
    }
    selectedRange = 2
}