由于 NavigationButton 不再可用,如何在 NavigationLink 中检查条件以导航到另一个视图?
NavigationLink(destination: Dashboard(userName: self.userId,
password: self.password), isActive: $showDashboard) {
Button(action: {
if self.userId.isEmpty || self.password.isEmpty {
self.isAlert = true
} else {
self.showDashboard = true
}
}) {
Text("Submit")
.foregroundColor(.white)
.font(.system(size: 22))
Dashboard()
}
.frame(minWidth: 150, idealWidth: 300, maxWidth: 450,
minHeight: 30, idealHeight: 40, maxHeight: 50, alignment: .center)
.background(Color(red: 81/255, green: 221/255, blue: 182/255))
.padding([.leading, .trailing], 20)
}
编辑:-
如果 userName 和 password 的长度大于16,我还想显示警报;如果长度大于10,则显示其他警报;如果长度为0,则显示空消息警报
答案 0 :(得分:0)
您可以执行以下操作:
NavigationView {
VStack {
NavigationLink(destination: Dashboard(userName: self.userId, password: self.password), isActive: $showDashboard) {
Text("")
}
Button(action: {
if self.userId.isEmpty || self.password.isEmpty {
self.isAlert = true
} else {
self.showDashboard = true
}
}) {
Text("Submit")
.foregroundColor(.green)
.font(.system(size: 22))
}
}
}
要记住的一点是,NavigationLink本身就是一个按钮,当按下它导航到destinationView
时,isActive
参数是强制执行此操作的一种方式(无需用户单击NavigationLink )。到目前为止,我不确定如何将逻辑嵌入到NavigationLinks中。
希望这会有所帮助:)
编辑:
您可以做的另一件事是
NavigationLink(destination:Dashboard(userName: self.userId, password: self.password)) {
Text("Submit")
}.disabled(self.userId.isEmpty || self.password.isEmpty )
这将禁用NavigationLink,直到两个输入字段都不为空。
答案 1 :(得分:0)
我不确定您是否要检查条件以确定NavigationLink
的目的地,或者是否将其禁用,但是此示例代码显示了如何执行这两项操作:
struct ContentView: View {
@State var userId = ""
@State var password = ""
var body: some View {
NavigationView {
NavigationLink(destination: (self.userId.isEmpty || self.password.isEmpty) ? AnyView(Dashboard(userName: self.userId, password: self.password)) : AnyView(Text("Different view")), isActive: Binding(get: {
return self.userId.isEmpty || self.password.isEmpty
}, set: { (_) in
})) {
Text("Navigate")
}
}
}
}
为isActive
创建自定义绑定以评估多种情况:
Binding(get: {
return self.userId.isEmpty || self.password.isEmpty
}, set: { (_) in
})
然后评估ternary statement中的条件,如果希望条件确定AnyView
导航到哪个视图,请确保对类型to return different kinds of views使用NavigationLink
:
(self.userId.isEmpty || self.password.isEmpty) ? AnyView(Dashboard(userName: self.userId, password: self.password) : AnyView(Text("Different view"))
编辑:如果不希望条件转换为nil
,则可以将另一个视图设置为false
:
(self.userId.isEmpty || self.password.isEmpty) ? AnyView(Dashboard(userName: self.userId, password: self.password) : nil
编辑2 :如果您希望在条件失败时显示警报,请使用上一行(带有nil
)作为NavigationLink的目的地,并添加一个警报Binding
的自定义isPresented
:
.alert(isPresented: Binding(get: {
return self.userId.isEmpty || self.password.isEmpty
}, set: { (_) in
})) {
Text("Alert message")
}
您可以使用要评估的变量(在本例中为ContentView
)将此警报添加到视图的任何子视图中。