skip to Main Content

The end goal is to display a table view controller made up of a model and some properties. The model is an array of list, where the list are the properties. An add bar button item takes user to another view controller with several text fields. The text fields correlate with the properties in array’s list.
The problem is I can not add the textfield input to the table view controller.
Outlets are connected. Segues are working. Data is being accepted. Just not transferring to Country array.

Aforementioned Tableviewcontroller:

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")]

My attempt to transfer data in 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")
    }

2

Answers


  1. if countries is the dataSource of the table this should help

    @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
    }
    
    Login or Signup to reply.
  2. Congratulations.

    Every ! Is a potential crash. I count 10 or so. Download Apple’s Swift book, learn how to use β€œif let”. Your users will thank you.

    The way you use string interpolation is horrendous. Safe:

    If let flag = flagTextField?.text, let name = nameTextField?.text, … {
        Create new country and add it
    } else {
        Handle error without crashing
    }
    

    Take the opportunity to learn about the guard statement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search