BookData.swift
import Foundation struct Book: Identifiable, Equatable { var id = UUID() var title:String var author:String var isRead = false } class Books: ObservableObject { @Published var booksData = [ Book(title: "風の又三郎", author: "宮沢賢治"), Book(title: "人間失格", author: "太宰治"), Book(title: "坊ちゃん", author: "夏目漱石"), Book(title: "遠野物語", author: "柳田國男"), Book(title: "生まれいずる悩み", author: "有島武郎"), Book(title: "舞姫", author: "森鴎外"), Book(title: "人間椅子", author: "江戸川乱歩"), Book(title: "人間レコード", author: "夢野久作"), Book(title: "山月記", author: "中島敦") ] func toggleIsRead(_ item: Book){ guard let index = booksData.firstIndex(of: item) else { return } booksData[index].isRead.toggle() } }
ContentView.swift
struct ContentView: View { @ObservedObject var books = Books() var body: some View { List(books.booksData) { item in BookView(item) .swipeActions(edge: .leading){ Button { books.toggleIsRead(item) } label: { if item.isRead { Label("未読にする", systemImage: "book.closed") } else { Label("既読にする", systemImage: "book.fill") } }.tint(.blue) } }.listStyle(.plain) } } @ViewBuilder func BookView(_ item:Book) -> some View { VStack(alignment: .leading){ Text(item.title).bold() Text(item.author) } .foregroundColor(item.isRead ? .gray : .black) .frame(height: 80) }
なるほどー