[Video Summary] Ch. 6.10 Searchable - adding a Pokemon-searching Search Bar to our SwiftUI Catch 'em All App (2024)
Mô tả nhanh
Video này hướng dẫn cách thêm thanh tìm kiếm vào ứng dụng "Catch 'em All" sử dụng SwiftUI, cùng với việc cải tiến code bằng cách tạo một method để xử lý việc tải dữ liệu trang, và cuối cùng là hiển thị lại số thứ tự của Pokemon trong danh sách.
Video
Mô tả chi tiết
Video này trình bày cách thêm thanh tìm kiếm vào ứng dụng "Catch 'em All", cải tiến code và hiển thị số thứ tự Pokemon.
Các bước thực hiện chính:
- Thêm Search Bar:
- Sử dụng modifier
.searchable(text:)vàoList. - Tạo biến
@State private var searchText = ""để lưu trữ text người dùng nhập. - Gán biến
searchTextvào modifier.searchable(text: $searchText).
- Sử dụng modifier
- Tách Code Load Dữ Liệu:
- Chuyển code trong
taskmodifier củaListvào methodloadNextIfNeeded(creature:)trong classCreatures. - Thêm tham số
creaturevào functionloadNextIfNeeded(creature:). - Thay thế
creatures.bằng các thuộc tính của classCreaturestrong method. - Sử dụng
idthay vìnameđể so sánh các đối tượng. - Thêm từ khóa
asynccho functionloadNextIfNeeded(creature:) - Gọi method
loadNextIfNeeded(creature:)trongtaskmodifier củaList, kèm theo từ khóaawait.
- Chuyển code trong
- Tạo Computed Property Cho Tìm Kiếm:
- Tạo computed property
searchResultskiểu[Creature]. - Trong
searchResults:- Nếu
searchTextrỗng, trả về toàn bộcreaturesarray.
- Nếu
- Ngược lại, sử dụng
filterđể lọc các phần tử trong creatures array cónamechứasearchText(sau khi đãcapitalized). - Thay thế
creatures.creaturesArraybằngsearchResultstrongList.
- Tạo computed property
- Hiển Thị Index của Pokemon:
- Tạo function
returnIndex(of creature: Creature) -> Intđể trả về index của Pokemon trong array. - Trong
returnIndex(of:):- Sử dụng
firstIndex(where:)để tìm index của một creature. - Trả về
0nếu không tìm thấy.
- Sử dụng
- Trong
labelcủaList, thêm string interpolation để hiển thị index:"\(returnIndex(of: creature)). \(creature.name.capitalized)"
- Tạo function
Chúc bạn học tập tốt!