0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】でTextFieldの検索ワードを使ってListのアイテムを.filterで絞り込む方法

Posted at

💡 概要
SwiftUIでTextFieldの入力内容をもとに、List内のアイテムをリアルタイムで絞り込み表示するサンプルです。
@Publishedとfilterを使うだけで、簡単に検索機能を実装できます。
🧱 完成イメージ
TextFieldに文字を入力すると、リスト内のアイテム名を含むものだけが表示されます。
例:
「スイカ」「キウイ」があり、「ス」と入力すると「スイカ」だけ表示されるようになります。
🧩 コード全体
✅ ViewModel(ListViewModel.swift)
スクリーンショット 0007-10-11 15.08.18.png
✅ View(ListView.swift)
スクリーンショット 0007-10-11 15.06.45.png
🧠 解説
自分の場合は、**ViewModelで計算プロパティ(computed property)**を作り、
それをViewのForEachで使っています。
このようにすることで、TextFieldに入力した検索ワードをもとに
items配列をリアルタイムで絞り込むことができ、
UIの更新も自動で反映されます。
✅ まとめ
@PublishedでsearchItemを監視
filterを使ってitemsを動的に絞り込み
計算プロパティでViewがシンプルに書ける
シンプルな構成ですが、SwiftUIの@Published+filter+ForEachの理解が深まる良い練習にもなります💪

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?