Pass binding that is dependent on another binding

Viewed 181

I'm rather new to SwiftUI, so please bear with in case I mix up the nomenclature.

I have an Int @State property that is used in a TabView to hold the current index. Then I have a function that takes a Binding<Bool> to display another view.

What I basically want to do is pass a condition into the function whenever my Int state reaches a given value.

Sample code:

import SwiftUI

struct FooTabView: View {
    @State private var selected = 0
    @State private var shouldShow: Bool = false

    var body: some View {
        TabView(selection: $selected) {
            Text("Hello")
                .tabItem {
                    Text("Foo")
                }.tag(0)
            Text("World")
                .tabItem {
                    Text("Bar")
                }.tag(1)
        }.anotherFunctionReturningAView(show: shouldShow)
    }
}

Lets say shouldShow should only be true, when selected is equal to 1. How would I do that?

2 Answers

I'm not sure if I understood your goal but you can try:

.anotherFunctionReturningAView(show: .constant(selected == 1))

You can use Proxy Binding, making it depend on your @State variable like that

struct ContentView: View {
    @State private var selected = 0
    @State private var shouldShow: Bool = false

    var body: some View {
        TabView(selection: $selected) {
            Text("Hello")
                .tabItem {
                    Text("Foo")
                }.tag(0)
            Text("World")
                .tabItem {
                    Text("Bar")
                }.tag(1)
        }.alert(isPresented: Binding<Bool>(
            get: {
                selected == 1 // << Here comes your condition
            }, set: {
                shouldShow = $0
            })
        , content: {
            Alert(title: Text("Test"))
        })
    }
}
Related