Skip to Content

List trong SwiftUI

1. Cơ bản

List { Text("Item 1") Text("Item 2") Text("Item 3") }

2. Dynamic List

struct Contact: Identifiable { let id = UUID() let name: String } struct ContactList: View { let contacts = [ Contact(name: "Alice"), Contact(name: "Bob"), Contact(name: "Charlie") ] var body: some View { List(contacts) { contact in Text(contact.name) } } }

3. List Styles

List { } .listStyle(.plain) .listStyle(.inset) .listStyle(.insetGrouped) .listStyle(.grouped) .listStyle(.sidebar)

4. Sections

List { Section("Favorites") { Text("Item 1") Text("Item 2") } Section("Recent") { Text("Item 3") Text("Item 4") } }

5. Swipe Actions

List { ForEach(items) { item in Text(item.name) .swipeActions(edge: .trailing) { Button(role: .destructive) { delete(item) } label: { Label("Delete", systemImage: "trash") } } .swipeActions(edge: .leading) { Button { favorite(item) } label: { Label("Favorite", systemImage: "star") } .tint(.yellow) } } }

6. Delete và Move

List { ForEach(items) { item in Text(item.name) } .onDelete { indexSet in items.remove(atOffsets: indexSet) } .onMove { from, to in items.move(fromOffsets: from, toOffset: to) } } .toolbar { EditButton() }

7. Selection

struct SelectableList: View { @State private var selection: Set<UUID> = [] let items: [Item] var body: some View { List(items, selection: $selection) { item in Text(item.name) } .toolbar { EditButton() } } }

8. Custom Row

struct ContactRow: View { let contact: Contact var body: some View { HStack { Image(systemName: "person.circle.fill") .font(.largeTitle) .foregroundColor(.blue) VStack(alignment: .leading) { Text(contact.name) .font(.headline) Text(contact.email) .font(.caption) .foregroundColor(.gray) } Spacer() } .padding(.vertical, 4) } } List(contacts) { contact in ContactRow(contact: contact) }

9. Pull to Refresh

List(items) { item in Text(item.name) } .refreshable { await loadData() }

📝 Tóm tắt

FeatureCode
Style.listStyle()
Delete.onDelete
Move.onMove
Swipe.swipeActions
Refresh.refreshable
Last updated on