Stanislav Poslavsky
Stanislav Poslavsky

Reputation: 2428

SwiftUI: transform Binding into another Binding

Is there a way to e.g. logically negate Binding<Bool>? For example, I've a state variable

@State var isDone = true

which I pass as a biding into different sub views. Then I want to use it e.g. with isActive in NavigationLink, so that it shows only when not isDone:

NavigationLink(destination: ..., isActive: ! self.$isDone ) // <- `!` means `not done`

Of course, I can invert my logic with isDone -> isNotDone, but it would be unnatural in many contexts. So is there any simple way to make inverse of a bool binding?

Upvotes: 7

Views: 4406

Answers (1)

Asperi
Asperi

Reputation: 258365

If I correctly understood you need the following:

extension Binding where Value == Bool {
    public func negate() -> Binding<Bool> {
        return Binding<Bool>(get:{ !self.wrappedValue }, 
            set: { self.wrappedValue = !$0})
    }
}

struct TestInvertBinding: View {
    @State var isDone = true
    var body: some View {
        NavigationView {
            NavigationLink(destination: Text("Details"), 
                isActive: self.$isDone.negate()) {
                Text("Navigate")
            }
        }
    }
}

struct TestInvertBinding_Previews: PreviewProvider {
    static var previews: some View {
        TestInvertBinding()
    }
}

Upvotes: 14

Related Questions