2

I'm still new to Swift, so please bear with me.

Currently I have loaded data from a JSON file and that is then displayed onto the individual cells.

I have a custom cell class which has the necessary label outlets (name and number).

What I want to do, is to retrieve data from a specified labels text when on a given row then pass it onto another ViewController.

e.g. Row 3 has two labels, "Data" and "2004". I have selected row 3 and would like to get this cells "2004" value and assign it to a variable that can be then passed to a different ViewController. ("2004" would be considered the number label outlet in my custom cell class i.e. cell.number)

Here is some code that may be of help:

Table View Controller

import UIKit

class TableViewController: UITableViewController, UINavigationControllerDelegate {

    @IBOutlet var segmentedSortOption: UISegmentedControl!
    var array : NSArray = DataClass.dataStruct.jsonResult["data"] as NSArray

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var myCell:cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as cell
        var upperCasedNames = array[indexPath.row]["name"] as? String

        if segmentedSortOption.selectedSegmentIndex == 0 {

            myCell.No.text = array[indexPath.row]["no"] as? String

        } else if segmentedSortOption.selectedSegmentIndex == 1 {

            if let unsortedEvents = DataClass.dataStruct.jsonResult["data"] as NSArray {

                let descriptor = NSSortDescriptor(key: "name", ascending: true, selector: "caseInsensitiveCompare:")
                let aToZ = unsortedEvents.sortedArrayUsingDescriptors([descriptor])

                myCell.No.text = aToZ[indexPath.row]["no"] as? String
            }  
        }    
        return myCell
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "selectedItem" {
            if let indexPath = self.tableView.indexPathForSelectedRow() {
                let destinationController = segue.destinationViewController as ViewController
                destinationController.eventData = indexPath.row as Int   
            }   
        } 

Custom Cell Class

import UIKit

class cell: UITableViewCell {

    @IBOutlet var name: UILabel!

    @IBOutlet var number: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

If you have any more questions, please do ask.

If you have a better alternative, please do suggest that as well.

Thanks!

EDIT: Forgot to mention a key issue. There is a segmented control that reorganises the data from the given order in the JSON file to an alphabetical order. The cells indexPath.row becomes useless in the instance of the A-Z view as the order is completely different.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Javz
  • 318
  • 1
  • 3
  • 13

2 Answers2

2

In your prepareForSegue you need to get the cell you is selected with cellForRowAtIndexPath(is not the same tableView(tableView: UITableView, cellForRowAtIndexPath ) and the pass it to the destinationController, see the following example:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "selectedItem" {
        if let indexPath = self.tableView.indexPathForSelectedRow() {

            // get the cell associated with the indexPath selected.
            let cell = self.tableView.cellForRowAtIndexPath(indexPath) as cell!

            // get the label text to pass to destinationController
            var text1 = cell.name.text
            var text2 = cell.number.text

            let destinationController = segue.destinationViewController as ViewController
            destinationController.eventData = indexPath.row as Int   
        }   
    } 
}

I hope this help you.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
  • Thank you very much! I CANNOT believe it was THIS simple!! More or less spent the entire day trying to figure this out lol Thanks again Victor, much appreciated :D – Javz Aug 13 '15 at 23:25
  • Glad to help you. It's always a good reference read the TableView Programming Guide of Apple, even when is in Objective-C yet!!, but you can learn a lot from the guide. – Victor Sigler Aug 14 '15 at 14:10
  • The irony is that I used the same code but placed it in didSelectRowAtIndex, didn't even strike me to place it there; but does make sense. And I shall definitely look into the guide from now on. Thanks again Victor :) – Javz Aug 14 '15 at 22:24
0

OK, I too am new to Swift, so bear with me. I see a few ways to do this.

1) You are throwing data into this tableview from a JSON file, right? So, depending on the structure of your project, maybe you can just get the index (row) clicked and use it to get the associated data from the JSON.

let indexPath = tableView.indexPathForSelectedRow();

Then pass that integer indexPath to whatever JSON parsing library you are using to get the associated data.

2) I'm not sure how the custom nature of your implementation changes things, but possibly this more generic question has your answer.

3) More of a hack-y solution, but maybe when you populate this UITableView you could set the tag of each cell to be its index, then you could just get it by tag and retrieve its label value that way (like in this SO answer)?

Community
  • 1
  • 1
Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
  • Thanks for the input, but I was using your first suggestion initially, but after the new A-Z sort, it makes that function redundant. I've also checked the first link, which was of no help since I was using a custom cell class, however the second link looks like it will come in handy in the near future. Thanks :) – Javz Aug 13 '15 at 23:22
  • Sure, sorry I didn't fully read/understand your question to begin with :) Anyway good luck! If you come up with a solution along the lines of my third idea feel free to suggest the code as an edit to the answer and I'll integrate it. – Max von Hippel Aug 13 '15 at 23:28