Javz
Javz

Reputation: 318

Get a selected label text from a selected row in a UITableViewController

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.

Upvotes: 2

Views: 4759

Answers (2)

Victor Sigler
Victor Sigler

Reputation: 23449

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.

Upvotes: 2

Max von Hippel
Max von Hippel

Reputation: 2970

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

Upvotes: 0

Related Questions