1. Conditional 条件运算符的使用
1.1 实现
/// 条件语句
struct ConditionalBootcamp: View {
@State var showCircle: Bool = false
@State var showRectangle: Bool = false
@State var isLoading: Bool = false
var body: some View {
//conditionalView1
conditionalView2
}
/// 方式二
var conditionalView2: some View{
VStack(spacing: 20) {
Button("Is Loading: \(isLoading.description)") {
isLoading.toggle()
}
if isLoading{
ProgressView()
}
Spacer()
}
}
/// 方式一
var conditionalView1: some View{
VStack(spacing: 20) {
Button("Circle Button: \(showCircle.description)") {
showCircle.toggle()
}
Button("Rectangle Button: \(showRectangle.description)") {
showRectangle.toggle()
}
if showCircle {
Circle()
.frame(width: 100, height: 100)
}
if showRectangle{
Rectangle()
.frame(width: 100, height: 100)
}
if showCircle && showRectangle{
RoundedRectangle(cornerRadius: 25)
.frame(width: 200, height: 100)
}
Spacer()
}
}
}
1.2 效果图:
1) 方式一:
2) 方式二:
2. Ternary 三目运算符的使用
2.1 实现
/// 三目运算符
struct TernaryBootcamp: View {
@State var isStartingState:Bool = false
var body: some View {
VStack{
// 按钮
Button("Button: \(isStartingState.description)") {
isStartingState.toggle()
}
// 文本
Text(isStartingState ? "Starting State" : "Ending State")
// 圆角矩形
RoundedRectangle(cornerRadius: isStartingState ? 25 : 0)
.fill(isStartingState ? Color.red : Color.blue)
.frame(width: isStartingState ? 200 : 50,
height: isStartingState ? 100 : 50)
Spacer()
}
}
}