将“正确”数据从UITableViewController中的选定单元格传递到ViewController

时间:2017-07-18 11:56:46

标签: ios json swift uitableview

我遇到了同样的问题here我还没想出如何将正确的数据从TableViewController传递到另一个ViewController。我从JSON获取数据我拥有我需要的一切,但是通过选择显示最后一行中的数据的任何行数据。我需要获取有关我选择TableViewController的确切行的信息。

import UIKit

class TableViewController: UITableViewController {

var TableData:Array< String > = Array < String >()

func getData(_ link: String) {
    let url: URL = URL(string: link)!
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "GET"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in
        guard let _: Data = data , let _: URLResponse = response , error == nil else {
            return
        }
        self.extractJSON(data!)
    })
    task.resume()
}

func extractJSON(_ data: Data) {
    let json: Any?
    do {
        json = try JSONSerialization.jsonObject(with: data, options: [])
    } catch {
        return
    }
    guard let dataList = json as? NSArray else {
        return
    }
    if let countriesList = json as? NSArray {
        for i in 0 ..< dataList.count {
            if let countriesObj = countriesList[i] as? NSDictionary {
                if let countryName = countriesObj["country"] as? String {
                    if let countryCode = countriesObj["code"] as? String {
                        TableData.append(countryName + " [" + countryCode + "]")
                        UserDefaults.standard.set(String(describing: countryName), forKey: "name")
                        UserDefaults.standard.set(String(describing: countryCode), forKey: "code")
                        UserDefaults.standard.synchronize()
                    }
                }
            }
        }
    }

    DispatchQueue.main.async(execute: {self.doTableRefresh()})
}

func doTableRefresh() {
    self.tableView.reloadData()
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.delegate = self
    self.tableView.dataSource = self
    getData("http://www.kaleidosblog.com/tutorial/tutorial.json")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return TableData.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = TableData[indexPath.row]

    return cell
}
}

2 个答案:

答案 0 :(得分:2)

您可以使用tableViewDidSelectRowAtIndexPath委托方法

let string = TableData[indexPath.row]

获取您的数据并将其传递给vc

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   let string = TableData[indexPath.row]

    let vc = // Your VC From Storyboard 
    vc.data =  string // 
    self.navigationController?.pushViewController(vc, animated: true)
}

答案 1 :(得分:0)

tableView:didSelectRowAtIndexPath: 

告诉委托者现在选择了指定的行。使用indexPath在tableView中找到新选定的行。 在下一个视图控制器中声明一个var。

var yourObject:String!

您可以使用所选单元格的索引路径访问所选单元格的数据,然后将数据发送到下一个视图控制器。访问下一个视图控制器yourObject的var并传递所需的数据。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let string = TableData[indexPath.row]

if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController ") as? SecondViewController {
    viewController.yourObject = yourObject
    if let navigator = navigationController {
        navigator.pushViewController(viewController, animated: true)
    }
  }
}