Swift,将UITableView部分传递给新视图控制器

时间:2016-01-29 23:57:46

标签: swift uitableview

如何在UITableView中传递当前单击的单元格的部分?

例如,假设我有:

  • 类别
    • post 2
    • post 3

其中category是节标题,posts的项目符号是UITableView中的单元格。

我想传递给单元标签和部分的新视图。

我知道如何传递标签我似乎无法获得当前部分

或者,有没有办法为每个单元格分配一个额外的值,比如数据库中的ID?

简短而甜蜜,如果可能的话,请把我带到某个地方,我是编程的新手,所以所有帮助都可以。

1 个答案:

答案 0 :(得分:1)

我想在你的第一个ViewController中,你有数据要填写UITableView。

这样的东西
var sectionTitles = ["Category1", "Category2"]
var postData = [["post1", "post2"],["anotherPost1", "anotherPost2"]]

单击行时委托方法didSelectRowAtIndexPath: 叫做。然后,您可以通过indexPath.section访问所选行。

示例

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

然后,您需要在第二个ViewController中创建变量 label sectionTitle

class SecondViewController : UIViewController {
    var label:String?
    var sectionTitle:String?
}