SwiftUI:将 Binding 转换为另一个 Binding

6

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

@State var isDone = true

我将其作为绑定传递到不同的子视图中。 然后我想在NavigationLink中使用它,例如与isActive一起使用,以便仅在not isDone时显示:

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

当然,我可以使用 isDone -> isNotDone 来反转我的逻辑,但在许多情况下这会不太自然。那么,有没有简单的方法来反转布尔绑定呢?
1个回答

11

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

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()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接