通过点击选项卡可切换视图的显示内容。
代码如下:
import SwiftUI
struct ContentView: View {
init() {
//初始选择项背影颜色
UISegmentedControl.appearance().selectedSegmentTintColor = .red
//初始title的参数
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.yellow], for: .selected)
}
@State private var selectedSida:SideOfTheForce = .breakfast//枚举初值
var body: some View {
NavigationView{
VStack{
HStack{
Picker("请选择", selection: $selectedSida){
ForEach(SideOfTheForce.allCases,id: .self){
Text($0.rawValue)//遍历枚举里的所有项
}
}
//设置为选项卡样式
.pickerStyle(SegmentedPickerStyle())
.padding()
}
Spacer()
ChooseMeals(sideOfTheForce: selectedSida)
.padding() //如果不填充会挡住选项卡,点击不了
Spacer()
}
.navigationTitle("选项卡")
}
}
}
//CaseIterable 提供其所有值的集合的类型。ForEach时通过使用allCases访问所有集合。
enum SideOfTheForce : String,CaseIterable{
case breakfast
case lunch
case dinner
case nightfood
}
struct ChooseMeals:View{
var sideOfTheForce:SideOfTheForce
var body: some View{
switch sideOfTheForce {
case .breakfast:
ShowMeal(meal:"1")
case .lunch:
ShowMeal(meal:"2")
case .dinner:
ShowMeal(meal:"3")
case .nightfood:
ShowMeal(meal:"4")
}
}
}
struct ShowMeal:View {
var meal:String
var body: some View{
//利用GeometryReader获取容量的高宽
GeometryReader{ geometry in
Text(meal)
.font(.system(size: min(geometry.size.width * 0.8,geometry.size.height * 0.8)))
.padding()
}
}
}
除非注明,网络人的文章均为原创,转载请以链接形式标明本文地址:https://www.55mx.com/post/113
《【SwiftUI实战】使用枚举类型与Picker实现选项卡》的网友评论(0)