以编程方式将UITableViewCell标签链接到下一个ViewController

时间:2016-12-19 10:04:18

标签: ios swift uitableview

我在一个ViewController中以编程方式创建了2个TableViewControllers:

// contents for labels in cells for tableviewcontrollers

let contents1 : [String] = ["One:","Two:","Three:","Four:","Five:"]

let contents2 : [String] = ["Six:","Seven:","Eight:","Nine:","Ten:"]

override func viewDidLoad() {
    super.viewDidLoad()

    table1.delegate = self
    table1.dataSource = self

    table2.delegate = self
    table2.dataSource = self   
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(tableView.tag == 1)
    {
        return contents1.count
    }
    else if (tableView.tag == 2)
    {
        return contents2.count
}
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

  let cell = tableView.dequeueReusableCell(withIdentifier: "cell",  for: indexPath as IndexPath )

    if (tableView.tag == 1)
    {
        cell.textLabel?.text = contents1[indexPath.row]
    }
    else if (tableView.tag == 2)
    {
        cell.textLabel?.text = contents2[indexPath.row]

    }
return cell
}

我的问题是,当我选择在不使用Segue的情况下显示下一个新的ViewController时,如何以编程方式链接第一个TableViewController“table1”的“Four:”标签?

2 个答案:

答案 0 :(得分:0)

您可以func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) if cell?.textLabel?.text == "Four" { // you can use you indexPath to compare as well let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController self.navigationController.pushViewController(secondViewController, animated: true) } } deSelectRowAt委托方法识别单元格选择,然后您可以进入下一个视图

Date

答案 1 :(得分:-1)

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = pets[indexPath.row]
    // Configure the cell...

    return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    myIndex = indexPath.row
    performSegue(withIdentifier: "segue", sender: self)