iOS SwiftUI-7 iOS13-List用法及搭配Toggle


Posted by John on 2021-01-13

  1. List取得各個Itme,各別設定id,並搭配Toggle範例
  2. 設定List Row高度、separator風格
  1. List取得各個Itme,各別設定id,並搭配Toggle範例

     struct Model {
         var id: Int = 0
         var name: String = ""
     }
     struct MainView: View {
         @State var items: [Model] = []
         func getCurList() {
             //getItemList()隨意只是改變items
             self.items = getItemList()
             print("items \(items.count)")
         }
         var body: some View {
             List {
                 //取得各個items 並且都設有對應的id,此方法可以搭配Toggle使用
                 ForEach(0..<items.count, id:\.self) { row in
                     var item = items[row]
                     let binding = Binding<Bool>(get: { () -> Bool in
                         return  item.status
                     }) { (newValue) in
                         item.status = newValue
                     }
                     //顯示左邊Labels 
                     Toggle(isOn: binding) {
                         Text(item.name)
                             .foregroundColor(.white)
                     }
                     //隱藏Labels 
                     Toggle("\(item.id)", isOn: binding).labelsHidden()
                 }
             }
         }
     }
    
     struct SubView: View {
         @State var items: [Model] = []
         var body: some View {
             List {
                 //每次直接取得item,並且設定對應的id
                 ForEach(items, id:\.id) { item in
    
                 }
             }
         }
     }
    
  2. 設定List Row高度、separator風格

     struct MainView: View {
         var body: some View {
             List {
                 ForEach(0..<items.count, id:\.self) { row in
    
                 }.listRowInsets(EdgeInsets())//設定Row padding
             }.environment(\.defaultMinListRowHeight, 20)
             //listRowInsets設定後,在設定這個defaultMinListRowHeight就可以改變row高度
             .onAppear {
                 //底線的風格
                 UITableView.appearance().separatorStyle = .singleLine
                 //底線顏色
                 UITableView.appearance().separatorColor = UIColor(red: 167/255.0, green: 167/255.0, blue: 167/255.0, alpha: 1)
                 //底線padding
                 UITableView.appearance().separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
             }
             .onDisappear {
                 //清除底線顏色
                 UITableView.appearance().separatorColor = .clear
                 //關閉底線
                 UITableView.appearance().separatorStyle = .none
             }
         }
     }
    

    最後更新時間:2021/01/14


##iOS #swift #SwiftUI #XCode #軟體語言 #程式設計







Related Posts

Closure 閉包

Closure 閉包

MTR04_0921

MTR04_0921

[Gitlab CI] 在pipelines中使用API取得artifacts

[Gitlab CI] 在pipelines中使用API取得artifacts


Comments