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

走远了吗. 提交于 2019-12-25 09:05:35

问题


I have a UITableviewController where I take a JSON file and break it down into various objects for display on my tableview (this works fine).

I've also created variables to store certain information from the cells generated in the tableview to be passed on to a detailViewController (text and images).

Using the 'prepare for segue' method I am able to pass the information I need to the detailViewController. However, I keep running into an issue where the data displayed in the detailViewController isn't the data of the cell selected but rather the data of what appears to the the last loaded cell on the table.

I am not using the didSelectRowAtIndexPath because it doesn't seem to do much better but create an additional segue screen (automatically).

In summary, my TableViewController displays about 4 cells at a time on the screen. regardless of which cell I select, the information passed to the DetailViewController is always the information on the fourth cell displayed on the screen.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Post Cell", forIndexPath: indexPath) as! TableViewCell

var dict = jsonArr[indexPath.row]
        cell.postTitle.text = dict["data"]!["post_title"] as? String
        cell.postTag.text = dict["data"]!["post_tags"] as? String
        cell.postAddress.text = dict["data"]!["post_address"] as? String

titleToPass = cell.postTitle.text
postTagToPass = cell.postTag.text
addressToPass = cell.postAddress.text



override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if (segue.identifier == "ListToDetail") {


            let viewController = segue.destinationViewController as! DetailPostViewController

            viewController.passedTitle = titleToPass
            viewController.passedPostTags = postTagToPass
            viewController.passedAddress = addressToPass


            }
    }

回答1:


cellForRowAtIndexPath gets called for every cell, so it makes sense that your variables will always have values matching the last cell to be updated.

Instead of setting the data you want to pass in that method, call indexPathForSelectedRow: in prepareForSegue and use the row of the index path to get the right things from jsonArr.



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

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