Passing the “correct” Data from the selected cell in a UITableViewController to a ViewController

和自甴很熟 提交于 2020-01-07 04:04:10

问题


I'm having the very same trouble here I have not figured out yet how to pass the correct data from TableViewController to another ViewController. I get data from JSON I have everything I need but by selecting any row data showing is the data in the last row. I need to get the information about the exact row I select the 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
}
}

回答1:


You can use tableViewDidSelectRowAtIndexPath Delegate Method

let string = TableData[indexPath.row]

to get your data and pass it to 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)
}



回答2:


tableView:didSelectRowAtIndexPath: 

Tells the delegate that the specified row is now selected. Use indexPath to locate the new selected row in tableView. Declare a var in your next view controller.

var yourObject:String!

You can access data of selected cell using indexpath of selected cell and thenceforth send data to next view controller. Access the var of next view controller yourObject and pass required data.

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


来源:https://stackoverflow.com/questions/45166116/passing-the-correct-data-from-the-selected-cell-in-a-uitableviewcontroller-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!