1

Following tutorials, I have the following code to show a tab view with 3 tab items all with an icon on them, When pressed they navigate between the three different views. This all works fine, however, I want to be able to handle the selection and only show views 2 or 3 if certain criteria are met.

Is there a way to get the selected value and check it then check my own criteria and then show the view is criteria is met, or show an alert if it is not saying they can't use that view at the moment.

Essentially I want to be able to intercept the selection value before it switches out the view, maybe I need to rewrite all of this but this is the functionality I'm looking for as this is how I had my previous app working using the old framework.

@State private var selection = 1

var body: some View
{
    TabbedView(selection: $selection)
    {
        View1().tabItemLabel(
            VStack
            {
                Image("icon")
                Text("")
            })
            .tag(1)

        View2().tabItemLabel(
            VStack 
            {
                Image("icon")
                Text("")
            }).tag(2)

        View3().tabItemLabel(
            VStack 
            {
                Image("icon")
                Text("")
            }).tag(3)
    }
}
Jobins John
  • 1,265
  • 23
  • 45
AngryDuck
  • 4,358
  • 13
  • 57
  • 91

1 Answers1

0

You can do it by changing the value of selection on tap. You can use .onAppear() method for a particular tab to check your condition:

@State private var selection = 1
var conditionSatisfied = false

var body: some View
{
TabbedView(selection: $selection)
{
    View1().tabItemLabel(
        VStack
        {
            Image("icon")
            Text("")
        })
        .tag(1)
    View2().tabItemLabel(
        VStack 
        {
            Image("icon")
            Text("")
        }).tag(2)
          .onAppear() {
               if !conditionSatisfied {
                 self.selection = 1
               }
          }
    View3().tabItemLabel(
        VStack 
        {
            Image("icon")
            Text("")
        }).tag(3)
           .onAppear() {
               if !conditionSatisfied {
                 self.selection = 1
               }
          }
    }
}
PKS
  • 141
  • 3