SwiftUI更新有关枚举变量更改的自定义视图
我在网格3x4上有个月的视图。每个子视图都是一个带有月份名称和状态的小框,选中/未选中。问题是。。。我想从父视图观察枚举变量,并取消选择除上次按下的按钮之外的所有按钮 现在我已经实现了下一个逻辑。最初,我选择了带有状态的当前月份。无(未选择月份)。当我按下JAN按钮时,我将currentMonthSelected==.jax传递到单月子视图,它将返回更改currentMonthSelected的回调,该回调将观察其他视图 ParentViewSwiftUI更新有关枚举变量更改的自定义视图,swiftui,Swiftui,我在网格3x4上有个月的视图。每个子视图都是一个带有月份名称和状态的小框,选中/未选中。问题是。。。我想从父视图观察枚举变量,并取消选择除上次按下的按钮之外的所有按钮 现在我已经实现了下一个逻辑。最初,我选择了带有状态的当前月份。无(未选择月份)。当我按下JAN按钮时,我将currentMonthSelected==.jax传递到单月子视图,它将返回更改currentMonthSelected的回调,该回调将观察其他视图 ParentView @State var currentMonthSel
@State var currentMonthSelected: MonthsTypes = .none
SingleButtonView(title: .jan, isSelected: currentMonthSelected == .jan ? true : false, action: { month in
self.currentMonthSelected = month
})
SingleButtonView(title: .feb, isSelected: currentMonthSelected == .feb ? true : false, action: { month in
self.currentMonthSelected = month
})
struct SingleButtonView: View {
var title: MonthsTypes = .none
@State var isSelected = false
var action: (MonthsTypes) -> ()
var body: some View {
VStack(spacing: 0){
Button(action: {
self.action(self.title)
}){
Spacer()
Text(title.rawValue.prefix(3))
.font(.Montserrat(weight: isSelected ? .SemiBold : .Regular, size: 16))
.foregroundColor(isSelected ? Color.white : Color.gray)
Spacer()
}
}
.frame(width: 80, height: 40)
.background(isSelected ? Color.white : Color.brand_purple)
}
}
单月子视图
@State var currentMonthSelected: MonthsTypes = .none
SingleButtonView(title: .jan, isSelected: currentMonthSelected == .jan ? true : false, action: { month in
self.currentMonthSelected = month
})
SingleButtonView(title: .feb, isSelected: currentMonthSelected == .feb ? true : false, action: { month in
self.currentMonthSelected = month
})
struct SingleButtonView: View {
var title: MonthsTypes = .none
@State var isSelected = false
var action: (MonthsTypes) -> ()
var body: some View {
VStack(spacing: 0){
Button(action: {
self.action(self.title)
}){
Spacer()
Text(title.rawValue.prefix(3))
.font(.Montserrat(weight: isSelected ? .SemiBold : .Regular, size: 16))
.foregroundColor(isSelected ? Color.white : Color.gray)
Spacer()
}
}
.frame(width: 80, height: 40)
.background(isSelected ? Color.white : Color.brand_purple)
}
}
通过一个视图模型,这样的视图层次结构更易于管理。下面是一个基于代码的方法演示(只需删除一些带有自定义字体/颜色的行,但这不会影响idea)