RDowns RDowns - 1 month ago 8
Swift Question

How do I extract a variable from a UITable DidSelectAtRow?

I have an instance where a user picks from a UITable. The selected record has a

name
and an
id
associated with it.

At the moment to verify the name and id are being correctly reported I am using

let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)



Country(name: Optional("England"), countryId: Optional("5"))


I want to be able to store that countryId in a variable so I can repopulate my UITable with data (Football Divisions) that match the countryId '5'

How do I do this?

This is my full script:

import UIKit

class PickTeamViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var teamsTableView: UITableView!

var pickedCountryID: Int?

var selectedCellCountryTitle: String?
var cellCountryId: Int?

struct Country {
var name: String?
var countryId: String?

init(_ dictionary: [String : String]) {
self.name = dictionary["name"]
self.countryId = dictionary["id"]
}
}


struct Divisions {
var divisionName: String?
var divisionId: String?
init(_ dictionary: [String : String]) {

self.divisionName = dictionary["name"]
self.divisionId = dictionary["country_id"]
}
}

struct Teams {
var teamName: String?
var newTeamId: String?

init(_ dictionary: [String : String]) {
self.teamName = dictionary["name"]

}
}

struct TeamId {

var newTeamId: String?

init(_ dictionary: [String : String]) {
self.newTeamId = dictionary["id"]

}
}

var newCountries = [Country]()
var newDivisions = [Divisions]()
var newTeams = [Teams]()
var newTeamId = [TeamId]()

override func viewDidAppear(_ animated: Bool) {


let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTeams.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "GET";

let task = URLSession.shared.dataTask(with: myUrl!) { (data: Data?, response: URLResponse?, error: Error?) in

DispatchQueue.main.async
{

if error != nil {
print("error=\(error)")
return
}

do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
print (json)

if let arr = json?["countries"] as? [[String:String]] {
self.newCountries = arr.flatMap { Country($0) }
self.teamsTableView.reloadData()

}


if let arr = json?["divisions"] as? [[String:String]] {
self.newDivisions = arr.flatMap { Divisions($0) }

}




if let arr = json?["teams"] as? [[String:String]] {
self.newTeams = arr.flatMap { Teams($0) }

}


self.teamsTableView.reloadData()
} catch{
print(error)
}
}
}
task.resume()


}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return self.newCountries.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let country = newCountries[indexPath.row]
let cell = UITableViewCell()

cell.textLabel?.text = country.name
cell.textLabel?.font = UIFont(name: "Avenir", size: 12)
cell.textLabel?.textColor = UIColor.black
cell.backgroundColor = UIColor.white

return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

cellCountryId = indexPath.row
// print (self.newCountries[cellCountryId!])
let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)
}

override func viewDidLoad() {
super.viewDidLoad()

self.teamsTableView.delegate = self
self.teamsTableView.dataSource = self

// Do any additional setup after loading the view.
}


}

Answer

As discussed in the comments you should use another view controller to show the details. In didSelectRowAtIndexPath method take out the selected country from newCountries array and pass it to the DetailViewController.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let countryDetailsVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryDetailsViewController") as! DetailViewController
    countryDetailsVC.country = selectedCountry
    present(countryDetailsVC, animated: true, completion: nil)
}

Now that you have the country Struct you can show its details in the DetailViewController.