import SwiftUI class Item: Identifiable { var uuid: Int; var title: String init(title: String) { self.title = title self.uuid = generatteID() } } func _generateID() -> () -> Int { var id = 0 return { id += 1 return id } } var generatteID = _generateID() struct ContentView: View { @State var list: [Item] = [ Item(title: "A"), Item(title: "B"), Item(title: "C"), Item(title: "D"), Item(title: "E"), ] func delItemBy(uuid: Int) { let index = list.firstIndex(where: { $0.uuid == uuid }) if index != nil { list.remove(at: index!) } } func push() { list.append(Item(title: "F")) } func remove() { list.removeLast() } var body: some View { NavigationView { List { ForEach(list) { item in Button(action: { self.delItemBy(uuid: item.uuid) }) { Text(item.title + item.uuid.description) } } } .navigationBarTitle(Text("List")) .navigationBarItems(leading: Button(action: { self.push() }) { Text("Append") }, trailing: Button(action: { self.remove()}) { Text("RemoveLast") }) } } } 複製代碼
func _generateID() -> () -> Int { var id = 0 return { id += 1 return id } } var generatteID = _generateID() 複製代碼
class Item: Identifiable { var uuid: Int; var title: String init(title: String) { self.title = title self.uuid = generatteID() } } 複製代碼
詳解參考註釋swift
struct ContentView: View { // 使用 @State 屬性包裹器,修飾 list 屬性,關聯視圖的關係。 // 修改屬性值,視圖也會更新 @State var list: [Item] = [ Item(title: "A"), Item(title: "B"), Item(title: "C"), Item(title: "D"), Item(title: "E"), ] // 刪除 list 裏的數據 func delItemBy(uuid: Int) { let index = list.firstIndex(where: { $0.uuid == uuid }) if index != nil { list.remove(at: index!) } } // 追加數據 func push() { list.append(Item(title: "F")) } // 刪除數據 func remove() { list.removeLast() } var body: some View { // 使用導航視圖 NavigationView { // 定義一個列表 List { // 循環數據源 ForEach(list) { item in // 使用按鈕,綁定事件 Button(action: { self.delItemBy(uuid: item.uuid) }) { Text(item.title + item.uuid.description) } } } .navigationBarTitle(Text("List")) // 設置導航視圖的 Title .navigationBarItems(leading: Button(action: { self.push() }) { Text("Append") }, trailing: Button(action: { self.remove()}) { Text("RemoveLast") }) // 設置頂部的按鈕 } } } 複製代碼
運行代碼xcode