在swiftui中,我如何在选择后才使导航链接激活?我附上了一张截图。我希望能够选择一个或多个选项,但不希望下一个按钮被高亮显示,直到至少一个选项被选中。
(截图)import SwiftUI
struct AudienceView: View {
@State var isOn_w = false
@State var isOn_m = false
@State var isOn_g = false
@State var isOn_b = false
var body: some View {
VStack {
Text("Audience")
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.font(.title2)
.frame(
minWidth: 0,
maxWidth: .infinity,
alignment: .center
)
Spacer()
ScrollView{
Toggle(isOn: $isOn_w)
{Text("Women")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
Toggle(isOn: $isOn_m)
{Text("Men")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
Toggle(isOn: $isOn_g)
{Text("Girls")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
Toggle(isOn: $isOn_b)
{Text("Boys")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
}
NavigationLink(destination: AgeCategoryView(), label: {Text("Next")})
.padding(.bottom)
}
}
}
您可以使用ObservableObject
:
struct ContentView: View {
var body: some View {
NavigationView {
AudienceView()
}
}
}
class AudienceViewModel: ObservableObject {
@Published var isOn_w = false {
didSet { isActive = isOn_w || isOn_m || isOn_g || isOn_b }
}
@Published var isOn_m = false {
didSet { isActive = isOn_w || isOn_m || isOn_g || isOn_b }
}
@Published var isOn_g = false {
didSet { isActive = isOn_w || isOn_m || isOn_g || isOn_b }
}
@Published var isOn_b = false {
didSet { isActive = isOn_w || isOn_m || isOn_g || isOn_b }
}
@Published var isActive = false
}
struct AudienceView: View {
@StateObject var model = AudienceViewModel()
var body: some View {
VStack {
Text("Audience")
.fontWeight(.bold)
.font(.title2)
.frame(
minWidth: 0,
maxWidth: .infinity,
alignment: .center
)
Spacer()
ScrollView {
Toggle(isOn: $model.isOn_w)
{Text("Women")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
Toggle(isOn: $model.isOn_m)
{Text("Men")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
Toggle(isOn: $model.isOn_g)
{Text("Girls")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
Toggle(isOn: $model.isOn_b)
{Text("Boys")
.WithDefaultButtonTextFormatting()
}
.WithDefaultToggleSelectedFormatting()
}
if model.isActive {
NavigationLink("Next", destination: AgeCategoryView()).padding(.bottom)
} else {
Text("Next").foregroundColor(.gray).padding(.bottom)
}
}
}
}
你也可以使用"快捷方式"使用变量,像这样:
if isOn_w || isOn_m || isOn_g || isOn_b {
NavigationLink("Next", destination: AgeCategoryView()).padding(.bottom)
} else {
Text("Next").foregroundColor(.gray).padding(.bottom)
}
您可以在导航链接中添加.opacity()
修饰符,以便仅在满足条件时显示它。您可以像这样为选择提供逻辑:
var selectionMade: Bool {
if isOn_w == true || isOn_m == true || isOn_g == true || isOn_b == true {
return true
} else {
return false
}
}
然后贴在你身上Navigation Link
:
NavigationLink(destination: AgeCategoryView(), label: {Text("Next")})
.padding(.bottom)
.opacity(selectionMade ? 1 : 0)