はじめに
Listの検索機能作成します。
サンプルアプリ
データ
Appleのサービスリストです。
同じような名前でわかりにくいです。
let appleServices = [
"App Store",
"Apple Account Card",
"Apple Arcade",
"Apple Books",
"Apple Business Essentials",
"Apple Business Manager",
"Apple Card",
"Apple Cash",
"Apple Fitness+",
"Apple ID",
"Apple Messages for Business",
"Apple Music",
"Apple Music radio",
"Apple Music Subscriptions",
"Apple Online Store",
"Apple Pay & Wallet",
"Apple School Manager",
"Apple TV Channels",
"Apple TV+",
"AppleCare on Device",
"Device Enrollment Program",
"Dictation",
"FaceTime",
"Find My",
"Game Center",
"Global Service Exchange",
"Health sharing with provider",
"HomeKit",
"HomeKit Secure Video",
"iCloud Account & Sign In",
"iCloud Backup",
"iCloud Bookmarks & Tabs",
"iCloud Calendar",
"iCloud Contacts",
"iCloud Drive",
"iCloud Keychain",
"iCloud Mail",
"iCloud Notes",
"iCloud Private Relay",
"iCloud Reminders",
"iCloud Storage Upgrades",
"iCloud Web Apps (iCloud.com)",
"iMessage",
"iOS Device Activation",
"iTunes Match",
"iTunes Store",
"iWork Collaboration",
"iWork for iCloud",
"Mac App Store",
"macOS Software Update",
"Mail Drop",
"Maps Display",
"Maps Routing & Navigation",
"Maps Search",
"Maps Traffic",
"News",
"Photos",
"Podcasts",
"Radio",
"Schooltime",
"Schoolwork",
"Screen Time",
"Sign in with Apple",
"Siri",
"Spotlight suggestions",
"Stocks",
"Volume Purchase Program",
"Walkie-Talkie",
"Weather",
"App Store",
"Apple Account Card",
"Apple Arcade",
"Apple Books",
"Apple Business Essentials",
"Apple Business Manager",
"Apple Card",
"Apple Cash",
"Apple Fitness+",
"Apple ID",
"Apple Messages for Business",
"Apple Music",
"Apple Music radio",
"Apple Music Subscriptions",
"Apple Online Store",
"Apple Pay & Wallet",
"Apple School Manager",
"Apple TV Channels",
"Apple TV+"
]
実装
import SwiftUI
struct ContentView: View {
@State private var searchText: String = ""
var body: some View {
NavigationStack {
List(appleServicesFiltered, id: \.self) { service in
Text(service)
}
.navigationTitle("Apple Services")
.searchable(text: $searchText)
}
}
private var appleServicesFiltered: [String] {
// MARK: 大文字小文字を区別しない
let searchResult = appleServices.filter { $0.localizedStandardContains(searchText) }
// MARK: 大文字小文字を区別する
// let searchResult = appleServices.filter { $0.contains(text) }
return searchText.isEmpty ? appleServices : searchResult
}
}
おわり
この記事書いてて気づいたんですけどsearchable
バグありますね。
検索バーにフォーカスが当たった時にNavigationBarの所が一瞬白くなります笑