这是我参与8月更文挑战的第10天,活动详情查看:8月更文挑战
一、EditorButton
实现下图效果
struct Item: Identifiable {
let id = UUID()
let title: String
}
struct ContentView: View {
@State var editMode = EditMode.inactive
@State private var items: [Item] = (0..<5).map { Item(title: "Item #\($0)") }
@State private var count = 0
var body: some View {
NavigationView{
List{
ForEach(items){item in
Text(item.title)
}.onDelete(perform: {offsets in
items.remove(atOffsets: offsets)
}).onMove(perform: { source, destination in
items.move(fromOffsets: source, toOffset: destination)
})
}.onAppear(){
count = items.count
}
.navigationBarTitle("List")
.navigationBarItems(leading: EditButton(), trailing: Button("Add", action: {
items.append(Item(title: "Item #\(count)"))
count += 1
})).environment(\.editMode, $editMode)
}
}
}
- 为
List增加.environment(\.editMode, $editMode)属性,就可以切换List的编辑模式。 navigationBarItems的leading按钮指定为EditButton(),它会随着editMode的变化而变化。ForEach增加onDelete属性,增加删除元素功能,参数offsets为要删除的items。ForEach增加onMove属性,增加移动元素功能,第一个参数source为被移动的items,第二个参数destination为要移动到的目的地。
二、ProgressView
默认使用ProgressView()是作为加载中动画来使用的。
如果手动指定.progressViewStyle(LinearProgressViewStyle())则为进度条。
ProgressView(value: 50, total: 100, label: () -> _, currentValueLabel: () -> _)
value为当前进度值。total指定总进度数值。label可以在进度条上方增加视图。反过来可以看做,进度条在视图下方。currentValueLabel可以在进度条下方增加视图。
通过在进度条上方或者下方指定视图的方式,可以实现一个全景进度条的既视感。如下图:
代码如下:
struct ContentView: View {
var body: some View {
// ProgressView(value: 50, total: 100) {
// } currentValueLabel: {
// Rectangle()
// }
ProgressView(value: 50, total: 100) {
Rectangle().foregroundColor(.gray)
}
}
}
value可以传入Binding 变量的方式控制进度条变化。
代码如下:
struct ContentView: View {
@State var value = CGFloat(5)
var body: some View {
ProgressView(value: value, total: 100) {
ScrollView{
Button(action: {
value += 5
}, label: {
Text("add").font(.title)
})
}
}
}
}
注意:进度值不要超过
total值,不然会引起报错。
- 自定义
ProgressView要创建自定义ProgressView,需要创建struct实现ProgressViewStyle协议的makeBody方法。
struct DarkBlueShadowProgressViewStyle: ProgressViewStyle {
func makeBody(configuration: Configuration) -> some View {
ProgressView(configuration)
.shadow(color: Color(red: 0, green: 0, blue: 0.6),
radius: 4.0, x: 1.0, y: 2.0)
}
}
指定ProgressViewStyle即可使之生效。
VStack(spacing: 50) {
ProgressView()
ProgressView(value: 0.75)
}
.progressViewStyle(DarkBlueShadowProgressViewStyle())