//
// ContentView.swift
// LearnCombine
//
// Created by wangxuncai on 2021/8/18
//
import SwiftUI
class ViewModel:ObservableObject{
@Published var allItems:[ItemModel] = datas
@Published var searchedItem:String = ""
var filtedItems:[ItemModel]{
searchedItem.isEmpty ? allItems : allItems.filter({ str in
str.name.lowercased().contains(searchedItem.lowercased())
})
}
}
struct ContentView:View{
@ObservedObject var vm = ViewModel()
var body: some View{
ZStack {
LinearGradient(gradient: Gradient(colors: [Color.purple,Color.blue]), startPoint: .bottom, endPoint: .top)
.edgesIgnoringSafeArea(.all)
NavigationView {
List{
ForEach(vm.filtedItems){item in
NavigationLink(item.name, destination: item.detailView)
}
}.searchable(text: $vm.searchedItem)
.navigationTitle(Text("Searchable"))
}
}
}
}
struct DetailView:View,Identifiable{
var id = UUID()
var detail:String
var body: some View{
ZStack{
LinearGradient(gradient: Gradient(colors: [Color.purple,Color.blue]), startPoint: .bottom, endPoint: .top)
.edgesIgnoringSafeArea(.all)
Text(detail)
}
}
}
struct ItemModel:Identifiable{
var id = UUID()
var name:String
var detailView:DetailView
}
let datas:[ItemModel] = [
ItemModel(name: "wangxuncai", detailView:DetailView(detail: "A teacher")),
ItemModel(name: "Lucy", detailView:DetailView(detail: "A worker")),
ItemModel(name: "Mike", detailView:DetailView(detail: "A seller")),
ItemModel(name: "Michale", detailView:DetailView(detail: "A driver")),
]
网友评论