[Video Summary] Ch. 6.10 Searchable - adding a Pokemon-searching Search Bar to our SwiftUI Catch 'em All App (2024)

SwiftUI 6 Th02 2025

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

Click vào hình dưới để mở:
Ch. 6.10 Searchable - adding a Pokemon-searching Search Bar to our SwiftUI Catch 'em All App (2024)

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.
Ch. 6.10 Searchable - adding a Pokemon-searching Search Bar to our SwiftUI Catch 'em All App (2024)

Các bước thực hiện chính:

  1. Thêm Search Bar:
    • Sử dụng modifier .searchable(text:) vào List.
    • Tạo biến @State private var searchText = "" để lưu trữ text người dùng nhập.
    • Gán biến searchText vào modifier .searchable(text: $searchText).
  2. Tách Code Load Dữ Liệu:
    • Chuyển code trong task modifier của List vào method loadNextIfNeeded(creature:) trong class Creatures.
    • Thêm tham số creature vào function loadNextIfNeeded(creature:).
    • Thay thế creatures. bằng các thuộc tính của class Creatures trong method.
    • Sử dụng id thay vì name để so sánh các đối tượng.
    • Thêm từ khóa async cho function loadNextIfNeeded(creature:)
    • Gọi method loadNextIfNeeded(creature:) trong task modifier của List, kèm theo từ khóa await.
  3. Tạo Computed Property Cho Tìm Kiếm:
    • Tạo computed property searchResults kiểu [Creature].
    • Trong searchResults:
      • Nếu searchText rỗng, trả về toàn bộcreatures array.
    • Ngược lại, sử dụng filter để lọc các phần tử trong creatures arrayname chứa searchText (sau khi đã capitalized).
    • Thay thế creatures.creaturesArray bằng searchResults trong List.
  4. 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ề 0 nếu không tìm thấy.
    • Trong label của List, thêm string interpolation để hiển thị index: "\(returnIndex(of: creature)). \(creature.name.capitalized)"


Chúc bạn học tập tốt!

Tags