这是我参与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())
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END