美文网首页SwiftUI
SwiftUI Ios15 新增searchable用法

SwiftUI Ios15 新增searchable用法

作者: 王勋才 | 来源:发表于2021-08-18 13:47 被阅读0次
    //
    //  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")),
    
    
    ]
    
    

    相关文章

      网友评论

        本文标题:SwiftUI Ios15 新增searchable用法

        本文链接:https://www.haomeiwen.com/subject/reegbltx.html