2

How do I pass the section of the current clicked cell in a UITableView?

for example, lets say I have:

  • Category
    • post
    • post 2
    • post 3

Where category is the section header and the bullets for posts are the cells in the UITableView.

I want to pass to the new view the cell label AND the section.

I know how to pass the label I just can't seem to get the current section

Or, Is there a way to assign an extra value to each cell, like the ID from the database?

Short and Sweet, please direct me to somewhere if possible, I am new to programming so all help will do.

JamesG
  • 1,552
  • 8
  • 39
  • 86

1 Answers1

1

I guess in your first ViewController you have your data to fill in the UITableView.

Something like

var sectionTitles = ["Category1", "Category2"]
var postData = [["post1", "post2"],["anotherPost1", "anotherPost2"]]

When clicking the row the delegate method didSelectRowAtIndexPath: is called. You can then access the selected row via indexPath.section.

Example

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewControllerWithIdentifier("identifier") as! SecondViewController

    vc.sectionTitle = self.sectionTitles[indexPath.section]
    vc.label = self.postData[indexPath.section][indexPath.row]
    self.navigationController?.pushViewController(vc, animated:true)
}

You will then need to create the variable label and sectionTitle in your second ViewController.

class SecondViewController : UIViewController {
    var label:String?
    var sectionTitle:String?
}
dehlen
  • 7,325
  • 4
  • 43
  • 71
  • when I change the end: MyViewController to the actual view controller I get the value of type 'viewContrller' has no member section – JamesG Jan 30 '16 at 00:19
  • What I want is to be able to assign the section title 'category' to a variable to pass to a new view along with the cell label – JamesG Jan 30 '16 at 00:20
  • Yes sure, because you need to create that variable section in your Viewcontroller. Let me edit my question to provide more detail. – dehlen Jan 30 '16 at 00:21
  • Can you explain what this is? instantiateViewControllerWithIdentifier("identifier") as! MyViewController – JamesG Jan 30 '16 at 00:28
  • It is referencing your UIViewController from its identifier you need to provide in your Storyboard. So you go to your Storyboard where you created your SecondViewController and provide the Storyboard ID with some unique identifier. You can then instantiate your SecondViewController via code like in the example above. For further reference you should try to find it here on stackoverflow or google. It is very basic and not objective of your original question. Eg. http://stackoverflow.com/questions/17088057/instantiateviewcontrollerwithidentifier-storyboard-id-set-but-still-not-workin – dehlen Jan 30 '16 at 00:32