通过单击表视图中的单元格 - Swift iOS打开新的视图控制器

Gre*_*ory 37 ios swift

我有以下onClick函数

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    let row = indexPath.row
    println("Row: \(row)")

    println(meetingArray[row] as! String)

}
Run Code Online (Sandbox Code Playgroud)

打印出单击的单元格上的文本.它工作正常.

我只是想知道如何设置一个函数来引导你到新的视图控制器

Een*_*dje 61

编程方式:

let destination = UIViewController() // Your destination
navigationController?.pushViewController(destination, animated: true)
Run Code Online (Sandbox Code Playgroud)

故事板:
首先,您必须为视图设置标识符.在下面的屏幕截图中,您可以看到输入标识符的位置.

截图

之后,您可以使用以下代码创建"目标"并将其推送到导航控制器:

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destination = storyboard.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
navigationController?.pushViewController(destination, animated: true)
Run Code Online (Sandbox Code Playgroud)

Segue:
首先你必须为你的segue设置一个标识符,如下所示:

segue1

segue2

performSegue(withIdentifier: "segue", sender: self)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue" {
        // Setup new view controller
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:更新为Swift 3.x


Sau*_*ati 7

在storyboard中,在Identity Inspector中设置viewController的storyboardId.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    let row = indexPath.row
    println("Row: \(row)")

    println(meetingArray[row] as! String)

    let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("storyBoardIdFor your new ViewController") as SecondViewController
    self.navigationController.pushViewController(secondViewController, animated: true)
}
Run Code Online (Sandbox Code Playgroud)