使用SwiftUi在Xcode中添加搜索栏-为了在我的位置列表中找到特定的位置

2skhul33  于 2023-03-28  发布在  Swift
关注(0)|答案(1)|浏览(201)

我在Swift中尝试为位置应用添加搜索栏时遇到此错误:
“错误无法在属性初始值设定项内使用示例成员'Location';属性初始值设定项在“self "可用之前运行”
此处发生错误:

private var listOfLocation = Location

完整代码

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var authentication: Authentication
    @State var searchText = ""
    private var listOfLocation = Location
    
    var body: some View {
        TabBar()
    }
    
    var Location: [String] {
        let lcLocations = listOfLocation.map { $0.lowercased() }
        
        return searchText == "" ? lcLocations : lcLocations.filter {
            $0.contains(searchText.lowercased())
        }
    }
}
        
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(MapViewModel())
    }
}

我试过使用一个懒惰的var,但仍然不起作用。我是Swift的新手,所以任何帮助都会非常感激。

cczfrluj

cczfrluj1#

感谢您的反馈。我能够通过将搜索函数添加到我的“LocationList”文件而不是ContentView来解决这个问题。除了添加“@State”属性来跟踪搜索查询之外,我还添加了一个计算属性来根据搜索查询过滤“locations”数组。

import SwiftUI

struct LocationList: View {
    var locations: [Location]
    
    @State private var searchText = ""

    var filteredLocations: [Location] {
        if searchText.isEmpty {
            return locations
        } else {
            return locations.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
        }
    }

    var body: some View {
        VStack {
            HStack {
                Text("\(filteredLocations.count) \(filteredLocations.count > 1 ? "locations": "location" )")
                    .font(.headline)
                    .fontWeight(.medium)
                    .opacity(0.7)

                Spacer()

            
            }

            LazyVGrid(columns: [GridItem(.adaptive(minimum: 160), spacing:15)], spacing: 15) {
                ForEach(filteredLocations) { location in
                    NavigationLink(destination: LocationView(location: location)) {
                        LocationCard(location: location)
                    }
                }
            }
            .padding(.top)

        }
        .padding(.horizontal)
        .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
        .disableAutocorrection(true)
    }
}

struct LocationList_Previews: PreviewProvider {
    static var previews: some View {
        ScrollView {
            LocationList(locations: Location.all)
        }
    }
}

相关问题