如何从UITable DidSelectAtRow中提取变量?

时间:2016-11-05 09:38:51

标签: ios swift uitableview

我有一个用户从UITable中选择的实例。所选记录包含name和与其关联的id

目前正在验证名称和ID是否正确报告我正在使用

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

国家/地区(名称:可选("英格兰"),countryId:可选(" 5"))

我希望能够将countryId存储在变量中,以便我可以使用与countryId' 5'

匹配的数据(足球分区)重新填充我的UITable

我该怎么做?

这是我的完整脚本:

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.
}


}

2 个答案:

答案 0 :(得分:0)

您的表格是从数组newCountries填充的。因此,要替换表的内容,您需要替换newCountries的内容并重新加载表。

但这不是一个非常明智的策略。最好显示具有不同表和不同数据数组的不同视图控制器。

答案 1 :(得分:0)

如评论中所述,您应该使用另一个视图控制器来显示详细信息。在didSelectRowAtIndexPath方法中,从newCountries数组中取出所选国家/地区,然后将其传递给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)
}

现在您已拥有国家/地区Struct,您可以在DetailViewController中显示其详细信息。