有人能指点我如何实现一个带有确认删除功能的简单列表,或者至少展示最佳实践。
如果删除部分是立即进行的并且去掉警告部分,下面的代码将起作用。不知何故,确认警告的呈现会使删除操作在错误的人员列表上进行。第一次删除还会给出控制台警告:
[TableView] Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc), and will also cause unnecessary performance overhead due to extra layout passes. Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the debugger and see what caused this to occur, so you can avoid this action altogether if possible, or defer it until the table view has been added to a window.
然而,我不知道如何解决这个问题,除非去掉警告。顺便说一句,在我的Mac更新Xcode之前的几周,这段精确的代码是可以工作的。
import Foundation
import SwiftUI
import Combine
struct Person: Identifiable{
var id: Int
var name: String
init(id: Int, name: String){
self.id = id
self.name = name
}
}
class People: ObservableObject{
@Published var people: [Person]
init(){
self.people = [
Person(id: 1, name:"One"),
Person(id: 2, name:"Two"),
Person(id: 3, name:"Three"),
Person(id: 4, name:"Four")]
}
}
struct ContentView: View {
@ObservedObject var mypeople: People = People()
@State private var showConfirm = false
@State private var idx = 0
func setDeletIndex(at idxs:IndexSet) {
self.showConfirm = true
self.idx = idxs.first!
}
func delete() {
self.mypeople.people.remove(at: idx)
}
var body: some View {
VStack {
List {
Text("Currently \(mypeople.people.count) persons").font(.footnote)
.alert(isPresented: $showConfirm) {
Alert(title: Text("Delete"), message: Text("Sure?"),
primaryButton: .cancel(),
secondaryButton: .destructive(Text("Delete")) {
self.delete()
})
}
ForEach(mypeople.people){ person in
Text("\(person.name)")
}.onDelete { self.setDeletIndex(at: $0) }
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}