UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Can someone help with binding/state loss during rotation events?

Forums > SwiftUI

my code is here:

https://stackoverflow.com/questions/76391885/swiftui-state-binding-selectedindex-state-lost-on-rotation-layout

basicslly what i think is happening is that as i rotate the device the views are thrown away and recreated and as such lose all state. how do i fix this without a 'global' somewhere?

2      

Hi,

You need to go "one level up" with the selectedItem @Binding, try with this:

QuickCalculationsView

struct QuickCalculationsView: View
{
    @Environment(\.horizontalSizeClass) var hSizeClass
    @Environment(\.verticalSizeClass)   var vSizeClass
    @State private var selectedItem = 0

    @ObservedObject var settings = MySettingsSingleton.shared

    var body: some View
    {
        ZStack
        {
            Color.brown
                .edgesIgnoringSafeArea(.all)

            GeometryReader
            { geometry in
                if geometry.size.height > geometry.size.width // PORTRAIT
                {
                    if      UIScreen.main.traitCollection.userInterfaceIdiom == .phone
                    {
                        portraitArrangement(Width: geometry.size.width, Height: geometry.size.height)
                    }
                    else if UIScreen.main.traitCollection.userInterfaceIdiom == .pad
                    {
                        if settings.isLeftHanded == YES
                        {
                            if hSizeClass == .compact
                            {
                                portraitArrangement(Width: geometry.size.width, Height: geometry.size.height)
                            }
                            else
                            {
                                landscapeArrangementLeftHanded(Width: geometry.size.width, Height: geometry.size.height)
                            }
                        }
                        else
                        {
                            if hSizeClass == .compact
                            {
                                portraitArrangement(Width: geometry.size.width, Height: geometry.size.height)
                            }
                            else
                            {
                                landscapeArrangementRightHanded(Width: geometry.size.width, Height: geometry.size.height)
                            }
                        }
                    }
                }
                else                                          // LANDSCAPE
                {
                    if      UIScreen.main.traitCollection.userInterfaceIdiom == .phone
                    {
                        if settings.isLeftHanded == YES
                        {
                            landscapeArrangementLeftHanded(Width: geometry.size.width, Height: geometry.size.height)
                        }
                        else
                        {
                            landscapeArrangementRightHanded(Width: geometry.size.width, Height: geometry.size.height)
                        }
                    }
                    else if UIScreen.main.traitCollection.userInterfaceIdiom == .pad
                    {
                        if settings.isLeftHanded == YES
                        {
                            if hSizeClass == .compact
                            {
                                portraitArrangement(Width: geometry.size.width, Height: geometry.size.height)
                            }
                            else
                            {
                                landscapeArrangementLeftHanded(Width: geometry.size.width, Height: geometry.size.height)
                            }
                        }
                        else
                        {
                            if hSizeClass == .compact
                            {
                                portraitArrangement(Width: geometry.size.width, Height: geometry.size.height)
                            }
                            else
                            {
                                landscapeArrangementRightHanded(Width: geometry.size.width, Height: geometry.size.height)
                            }
                        }
                    }
                }
            }
        }
    }

    @ViewBuilder func portraitArrangement(Width width: CGFloat, Height height: CGFloat) -> some View
    {
        VStack
        {
            CalculationTabView(selectedItem: $selectedItem)
                .frame(width: width, height: 0.6 * height)

            NumberPadView()
                .frame(width: width, height: 0.4 * height)
        }
    }

    @ViewBuilder func landscapeArrangementLeftHanded(Width width: CGFloat, Height height: CGFloat) -> some View
    {
        HStack
        {
            NumberPadView()
                .frame(width: 0.4 * width, height: height)

            CalculationTabView(selectedItem: $selectedItem)
                .frame(width: 0.6 * width, height: height)
        }
    }

    @ViewBuilder func landscapeArrangementRightHanded(Width width: CGFloat, Height height: CGFloat) -> some View
    {
        HStack
        {
            CalculationTabView(selectedItem: $selectedItem)
                .frame(width: 0.6 * width, height: height)

            NumberPadView()
                .frame(width: 0.4 * width, height: height)
        }
    }
}

CalculationTabView

struct CalculationTabView: View
{
  private        let id                   : UUID = UUID()
  @State private var numberOfCalculations : Int    = 9 // Indexed from 0
  @Binding public  var selectedItem         : Int
  private        let width                : CGFloat = 64.0
  private        let arrayOfColors        : [Color] = [Color.pink, Color.mint, Color.purple, Color.cyan, Color.yellow, Color.teal,
                                                       Color.red,      Color.blue,      Color.green,  Color.gray, Color.indigo, Color.white]
  private        let arrayOfText          : [Text]  = [Text("One"),   Text("Two"),   Text("Three"), Text("Four"), Text("Five"),
                                                       Text("Six"),   Text("Seven"), Text("Eight"), Text("Nine"), Text("Ten")]

  var body: some View
  {
    HStack
    {
      VStack
      {
        VerticalSelectableTabBar(numberOfItems: $numberOfCalculations, selectedIndex: $selectedItem, content: arrayOfText)
          .frame(width: width)
      }

      arrayOfColors[selectedItem]
        .padding(.top, 20)
        .padding(.trailing, 10)
    }
  }
}

2      

Hi. thank you so much for your reply.

Doesn't this solution break the concept of it being a reusable view? If the core mechanic is stored 'outside' of the view itself, this would break core software engineering concepts.

is there another way that doesnt violate them and keeps the component reusable?

2      

Well the other way i could think of is using @Appstorage and storing the selected item that way, but maybe somebody else has a better idea.

2      

Doesn't this seem like a fundamental flaw in SwiftUI?

2      

I made a small class as the 'source of truth'. It's working now, but I'm still unhappy that I had to do that. Thanks for your help.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.