SwiftUI:将绑定转换为另一个绑定 [英] SwiftUI: transform Binding into another Binding
本文介绍了SwiftUI:将绑定转换为另一个绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法例如逻辑否定 Binding
?例如,我有一个状态变量
Is there a way to e.g. logically negate Binding<Bool>
? For example, I've a state variable
@State var isDone = true
我将其作为投标传递到不同的子视图中.然后我想使用它,例如在 NavigationLink
中使用 isActive
,这样它只在 not isDone
时显示:
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`
当然,我可以用 isDone -> 来反转我的逻辑.isNotDone
,但在许多情况下它是不自然的.那么有没有简单的方法来反转 bool 绑定?
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?
推荐答案
如果我理解正确,您需要以下内容:
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()
}
}
这篇关于SwiftUI:将绑定转换为另一个绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文