SwiftUI List中2020教程,如何高效添加新元素?

2026-05-28 09:461阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计252个文字,预计阅读时间需要2分钟。

SwiftUI List中2020教程,如何高效添加新元素?

功能说明:使用List循环显示array内容,并使用.self作为id,更新List内容,使用TextField基础使用。

代码:

swiftimport SwiftUI

struct ListAddItemView: View { @State var products=[手机, 电脑, 水杯] @State var pNam=

var body: some View { VStack { List { ForEach(products, id: \.self) { item in Text(item) } } .onAppear { updateList() }

TextField(添加新项目, text: $pNam) .padding() .onChange(of: pNam) { _ in updateList() }

Button(action: { if !pNam.isEmpty { products.append(pNam) pNam= } }) { Text(添加) } } }

func updateList() { // 更新List内容 }}

功能说明

  • 如何使用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) } } } }

效果

SwiftUI List中2020教程,如何高效添加新元素?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计252个文字,预计阅读时间需要2分钟。

SwiftUI List中2020教程,如何高效添加新元素?

功能说明:使用List循环显示array内容,并使用.self作为id,更新List内容,使用TextField基础使用。

代码:

swiftimport SwiftUI

struct ListAddItemView: View { @State var products=[手机, 电脑, 水杯] @State var pNam=

var body: some View { VStack { List { ForEach(products, id: \.self) { item in Text(item) } } .onAppear { updateList() }

TextField(添加新项目, text: $pNam) .padding() .onChange(of: pNam) { _ in updateList() }

Button(action: { if !pNam.isEmpty { products.append(pNam) pNam= } }) { Text(添加) } } }

func updateList() { // 更新List内容 }}

功能说明

  • 如何使用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) } } } }

效果

SwiftUI List中2020教程,如何高效添加新元素?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。