SwiftUI:将绑定转换为另一个绑定

Sta*_*sky 2 swiftui

有没有办法,例如逻辑否定Binding<Bool>?例如,我有一个状态变量

@State var isDone = true
Run Code Online (Sandbox Code Playgroud)

我将其作为投标传递给不同的子视图。然后我想将它与isActivein一起使用NavigationLink,以便它仅在not isDone以下情况下显示:

NavigationLink(destination: ..., isActive: ! self.$isDone ) // <- `!` means `not done`
Run Code Online (Sandbox Code Playgroud)

当然,我可以用 反转我的逻辑isDone -> isNotDone,但在许多情况下这将是不自然的。那么有没有简单的方法来反转 bool 绑定?

Asp*_*eri 5

如果我理解正确,您需要以下内容:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)