我是SwiftUI的新手,我正在努力学习它。在我的测试项目中,我想在List
中进行搜索,但在我看到的教程中,没有任何教程在另一个文件中使用struct
模型。我不知道该怎么办。我试着写点东西,但没有成功。你能帮我处理一下吗?提前感谢您的帮助。我把我的代码在下面检查:
ContentView.swift
import SwiftUI
struct ContentView: View {
@State private var searchText: String = ""
@State private var filteredText: [String] = []
var body: some View {
NavigationView {
VStack {
List {
ForEach(myFavorites) {favorite in
Section(header: Text(favorite.title)) {
ForEach(favorite.elements) { element in
NavigationLink(destination: DetailsView(chosenFavoriteElement: element)) {
Text(element.name)
}
}
}
}
}.navigationBarTitle("Favorite Book App").navigationBarTitleDisplayMode(.inline)
.searchable(text: $searchText).onChange(of: searchText) { search in
//I didn't wrote anyting down here
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
字符串
FavoriteModel.swift
import Foundation
struct FavoriteModel : Identifiable {
var id = UUID()
var title : String
var elements : [FavoriteElements]
}
struct FavoriteElements : Identifiable {
var id = UUID()
var name : String
var imageName : String
var description : String
}
let macOS = FavoriteElements(name: "MacOS", imageName: "macosventura", description: "MacOS 13
Ventura")
let windows = FavoriteElements(name: "Windows", imageName: "windows11", description: "Windows 11")
let borusanMannesmann = FavoriteElements(name: "Borusan Mannesmann", imageName: "borusanlogo", description: "Borusan Mannesmann Boru A.Ş.")
let aselsan = FavoriteElements(name: "Aselsan", imageName: "aselsan", description: "Aselsan Askeri Sanayi")
let favoriteOperatingSystems = FavoriteModel(title: "Favorite Operating Systems", elements: [macOS, windows])
let favoriteCompanies = FavoriteModel(title: "Favorite Companies", elements: [borusanMannesmann, aselsan])
let myFavorites = [favoriteOperatingSystems, favoriteCompanies]
型
1条答案
按热度按时间slmsl1lt1#
您应该使用
@State
跟踪当前列表显示的项目:字符串
如果
myFavorites
不是全局常量,而是self
中的其他常量,则可以在onAppear
中赋值。在您的
ForEach
es中使用此@State
:型
当
searchText
发生变化时,只需根据搜索文本更新状态即可。型
您可以在
updateFilteredFavorites
中执行任何类型的过滤。举例来说:型