首页 > 解决方案 > Swift IOS:如何使用用户输入添加到列表数组?

问题描述

最终目标是显示一个由模型和一些属性组成的表格视图控制器。模型是一个列表数组,其中列表是属性。添加栏按钮项将用户带到另一个具有多个文本字段的视图控制器。文本字段与数组列表中的属性相关。问题是我无法将文本字段输入添加到表格视图控制器。插座已连接。赛格斯正在工作。正在接受数据。只是不转移到国家阵列。

上述 Tableview 控制器:

public var countries: [Country] = [

    Country(flag: "", name: "United States of America", region: "North America", population: "328.2m"),
    Country(flag: "", name: "Ethiopia", region: "Horn of Africa", population: "105m"),
    Country(flag: "", name: "Greece", region: "South Eastern Europe", population: "10.77m"),
    Country(flag: "", name: "Kyrgystan", region: "Central", population: "6.2m"),
    Country(flag: "", name: "Vatican City", region: "Europe", population: "1000"),
    Country(flag: "", name: "Japan", region: "Northwestern Ring of Fire", population: "126.3m"),
    Country(flag: "", name: "South Sudan", region: "North Africa", population: "11.6m")]

我尝试在 addviewcontroller 中传输数据:

   @IBAction func submitCountryTapped(_ sender: Any) {
    newCountry = (Country(flag: "\(flagTextfield!.text!)", name: "\(nameTextfield!.text!)", region: "\(regionTextfield!.text!)", population: "\(popTextfield!.text!)"))
    countries.append(newCountry)
    print("\(flagTextfield!.text!) \(nameTextfield!.text!) has been added")
    }

标签: iosswiftxcode

解决方案


如果国家是表格的数据源,这应该会有所帮助

@IBAction func submitCountryTapped(_ sender: Any) {
    newCountry = (Country(flag: "\(flagTextfield!.text!)", name: "\(nameTextfield!.text!)", region: "\(regionTextfield!.text!)", population: "\(popTextfield!.text!)"))
    countries.append(newCountry)
    print("\(flagTextfield!.text!) \(nameTextfield!.text!) has been added")

    tableView.reloadData() // This is necessary
}

推荐阅读