SwiftUI 中級List如何添加新內容(2020年教程)

功能說明

  • 如何使用List循環顯示array內容
  • .self 做爲id的使用
  • 如何更新List內容
  • TextField基礎使用

代碼

import SwiftUI

struct ListAddItemView: View {
    @State var products = ["手機","電腦","水杯"]
    @State var pName:String = ""
    var body: some View {
        VStack{
            TextField("新商品:",text: self.$pName)
            Button(action:{
                print("hello")
                if (self.pName != "")
                {
                    self.products.append(self.pName)
                    self.pName = ""
                    
                }
                
            }){
                Text("添加一個商品")
            }
            
            List(products,id:\.self){ item in
                Text(item)
                
            }
            
        }
        
        
    }
}

效果

Jietu20200123-232204@2x.jpg

相關文章
相關標籤/搜索