2023年8月29日 星期二

[iOS][Swift][App] 實作搜尋建議

Photo by Ketut Subiyanto

簡單記錄一下實作搜尋建議的方法,完整的程式在下方

struct ContentView: View {
    @State private var searchText = ""
    @State private var selectedSuggestion = ""
    // 建議列表
    @State private var suggestions: [String] = ["Apple 蘋果", "ALLSAINTS", "BOTTEGA VENETA", "COSME DECORTE 黛珂", "Nike 耐吉", "Dell 戴爾", "COS", "Zara", "Emilie Louis", "L.ERICKSON", "SPRAYGROUND", "gubami Social-法式tapas餐廳", "Sarabeth's"]
    @State private var showSuggestions = false
    
    var body: some View {
        VStack {
	    // 搜尋欄位
            TextField("Search", text: $searchText)
                .padding(.horizontal, 15)
                .padding(.vertical, 10)
                .background(Color(.systemGray6))
                .cornerRadius(8)
                .padding(.top, 10)
                .padding(.bottom, 5)
                .onChange(of: searchText) { newValue in
                    showSuggestions = !newValue.isEmpty
                }
            
            // 選擇搜尋建議後的顯示
            if !selectedSuggestion.isEmpty {
                Text("Selected: \(selectedSuggestion)")
                    .padding(.top, 10)
            }
                        
            if showSuggestions {
                List {
                    ForEach(filteredSuggestions, id: \.self) { suggestion in
                        Text(suggestion)
                            .onTapGesture {
                                selectedSuggestion = suggestion
                                searchText = ""  // 清空 TextField
                                showSuggestions = false  // 隱藏建議列表
                            }
                    }
                    if filteredSuggestions.isEmpty {
                        Text("找不到品牌")
                            .foregroundColor(.gray)
                    }
                }
                .background(Color.white)
                .cornerRadius(8)
                .shadow(radius: 5)
                .padding()
            }
            Spacer()  // 添加一個間距,以便頁面內容和建議列表不重疊
        }
        .padding()
        
        var filteredSuggestions: [String] {
            if searchText.isEmpty {
                return []
            }
            return suggestions.filter({ $0.localizedCaseInsensitiveContains(searchText) })
        }
    }
}

沒有留言:

張貼留言