1. SafeArea 的使用
1.1 文字在安全区域内使用
1)实现
/// 文字安全区域
var textSafeArea: some View {
ZStack {
// background 背景忽略安全区域
//.edgesIgnoringSafeArea(.all)
Color.blue
.ignoresSafeArea()
// forground 前景
VStack {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)
}
}}
2) 效果图:
1.2 ScrollView 在安全区域内使用
1)实现
/// scrollView 安全区域
var scrollViewSafeArea: some View {
ScrollView{
VStack {
Text("Title goes here")
.font(.largeTitle)
.frame(maxWidth: .infinity, alignment: .leading)
// 循环
ForEach(0..<10) { index in
RoundedRectangle(cornerRadius: 25.0)
.fill(Color.white)
.frame(height: 150)
.shadow(radius: 10)
.padding(20)
}
}
}
//.background(Color.blue)
.background(
Color.red
// 背景忽略安全区域
//.edgesIgnoringSafeArea(.all) // old
.ignoresSafeArea()
)
}
2) 效果图:
2. Button 的使用
2.1 实现
struct ButtonsBootcamp: View {
@State var title:String = "This is my title"
var body: some View {
VStack(spacing: 20, content: {
Text(title)
Button("Press me") {
title = "Button was pressed"
}
.accentColor(.red) // 设置文字颜色
Button {
title = "Button #2 was pressed"
} label: {
Text("Save".uppercased())
.font(.headline)
.fontWeight(.semibold)
.foregroundColor(.white)
.padding()
.padding(.horizontal, 20)
.background(
Color.blue
.cornerRadius(10)
.shadow(radius: 10)
)
}
Button {
title = "Button #3"
} label: {
Circle()
.fill(Color.white)
.frame(width: 75, height: 75)
.shadow(radius: 10)
.overlay(
Image(systemName: "heart.fill")
.font(.largeTitle)
.foregroundColor(Color.red)
)
}
Button {
title = "Button #4"
} label: {
Text("Finish".uppercased())
.font(.caption)
.bold()
.foregroundColor(.gray)
.padding()
.padding(.horizontal, 10)
.background(
Capsule().stroke(Color.gray, lineWidth: 2.0)
)
}
})
}
}
2.2 效果图:
3. State 的使用
3.1 说明
1.1 State 定义 backgroundColor: 告诉 View 视图观察 , backgroundColor 这个变量的状态是背景颜色,它可能会改变,如果变量的状态确实改变了,我们会去更新视图,所以通过 State ,View 视图总会看到 backgroundColor 这个背景颜色,所以这个背景颜色在任何引用它的地方被改变,它也会在视图中发生变化
1.2 State 可以应用几乎任何类型的变量
3.2 实现
// State 属性包装
struct StateBootcamp: View {
//State : 告诉 View 视图观察 , backgroundColor 这个变量的状态是背景颜色,它可能会改变
// 如果变量的状态确实改变了,我们会去更新视图,所以通过 State ,View 视图总会看到 backgroundColor
// 这个背景颜色,所以这个背景颜色在任何引用它的地方被改变,它也会在视图中发生变化
// State 可以应用几乎任何类型的变量
@State var backgroundColor: Color = Color.green
@State var myTitle: String = "My title"
@State var count: Int = 0
var body: some View {
ZStack{
// background
backgroundColor
.ignoresSafeArea()
// Content
VStack(spacing: 20) {
Text(myTitle)
.font(.title)
Text("Count: \(count)")
.font(.headline)
.underline()
HStack(spacing: 20) {
Button("Button 1") {
backgroundColor = .red
myTitle = "Button 1 was pressed"
count += 1
}
Button("Button 2") {
backgroundColor = .purple
myTitle = "Button 2 was pressed"
count -= 1
}
}
}.foregroundColor(.white)
}
}
}