Dynamic ordering of HStack with SwiftUI?

Hello,


I'm trying to craft a really specific beavior with SwiftUI: implementing a dynamic ordering of HStack/VStack.


That's something really easy to do with UIKit but I can't figure out how I can do that with SwiftUI.


The context is simple, I'm writing a navigation app for pilots, and the goal is to make the app usable with one hand in a bumpy environment. That mean fixed iPad on the dash, and all active conrols available from a unique lower corner (so the palm can be maintained by the corner itself).


And the goal is to have one settings to set the app to be used from the lower left or right concern depending of the dash setup.


Any idea how I can do that with SwiftUI?

Replies

I'm doing something similar, and here's an example of the technique that I use:


struct DynamicStackView: View {
    /// The key indicating the contents of the dynamic stack
    enum Indicator : String, CaseIterable {
        case altimeter, airspeed, vspeed, attitude, heading, turn
    }

    /// The indicators that are visible in the stack; this
    func visibleIndicators() -> [Indicator] {
        return Indicator.allCases.shuffled() // or whatever order you want…
    }

    /// Vends a view for the given indicator key
    func indicatorView(for indicator: Indicator) -> some View {
        switch indicator {
        case .altimeter:
            return Text("Too High!")
        case .airspeed:
            return Text("Too Fast!")
        case .vspeed:
            return Text("Going Up!")
        case .attitude:
            return Text("Banking!")
        case .heading:
            return Text("Wrong Way!")
        case .turn:
            return Text("Uncoordinated!")
        }
    }

    /// Builds the dynamic stack of indicators based on the indicator order returned from `visibleIndicators()`
    var dynamicStack: some View {
        HStack {
            ForEach(visibleIndicators(), id: \.self, content: self.indicatorView(for:))
        }
    }

    var body: some View {
        dynamicStack
    }

}


Good luck with the app! I'm a pilot too, so let me know if you'd like my feedback on the design.