swiftUI combine 实现简单TodoList(二)

2020-09-10  本文已影响0人  garyZlot

目标:任务删除,任务编辑

1.任务删除

任务删除很简单,不用自己添加手势代码。SwiftUI提供了onDelete()修饰符,可用于控制如何从集合中删除对象。创建一个使用ForEach显示的行列表,然后将onDelete()附加到该ForEach,以便用户可以删除不需要的行。

ForEach(todoManager.todos) { todo in
    VStack {
        Text(todo.name)
            .font(.title)
        Text(todo.desc)
            .font(.subheadline)
    }
}.onDelete(perform:deleteRow)

struct ContentView 中添加删除fun

func deleteRow(at offsets:IndexSet) { 
    todoManager.todos.remove(atOffsets: offsets)
}
运行效果
WX20200911-144448@2x.png

2.任务编辑

新建SwiftUI View文件TodoDetail.swift, 添加两个TextField和一个更新的按钮,大致跟Add页面一致。

var body: some View {
        VStack {
            Text("TODO Detail")
            TextField("输入任务", text: $todo.name)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
            TextField("输入任务描述", text: $todo.desc)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
            Button(action: {
            }) {
                Text("Update")
            }
        }
    }

添加@State变量todo来存储数据

@State var todo: todo

preview 效果


任务详情

回到List页面使用NavigationLink添加跳转,ContentView.swift

NavigationView {
    List {
        ForEach(todoManager.todos) { todo in
            NavigationLink(destination: TodoDetail(todo: todo)){
                VStack {
                    Text(todo.name)
                        .font(.title)
                    Text(todo.desc)
                        .font(.subheadline)
                }
            }
        }.onDelete(perform:deleteRow)
    }
    .navigationBarTitle(Text("TODO List"))
}

把todo对象通过参数传到detail页面, 这里要注意把整个List放到NavigationView中,否则链接没法跳转。

detail 页面update 事件

因为都是值传递,不能通过绑定变量todo来更新数据。这里使用@EnvironmentObject TodoManager 来直接更新数组。

@EnvironmentObject var todoManager: TodoManager

var todoIndex: Int {
    todoManager.todos.firstIndex(where: { $0.id == todo.id })!
}

添加变量 todoIndex 来定位当前todo对象, update按钮事件更新当前对象

self.todoManager.todos[self.todoIndex] = self.todo

更新完了,使用PresentationMode,返回List页面

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

//update按钮事件
self.todoManager.todos[self.todoIndex] = self.todo
self.presentationMode.wrappedValue.dismiss()

Over~
源码 https://github.com/garyZlot/TodoList

上一篇下一篇

猜你喜欢

热点阅读