通过单击表视图中的单元格打开新的视图控制器 – Swift iOS
我有以下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) }
打印出单击单元格上的文本。 它工作正常。
我只是想知道你将如何设置一个函数,将您引导到新的视图控制器
编程方式:
let destination = UIViewController() // Your destination navigationController?.pushViewController(destination, animated: true)
故事板:
首先,你必须为你的视图设置一个标识符。 在下面的屏幕截图中,您可以看到在哪里input标识符。
之后,您可以使用以下代码创build“目标”并将其推送到导航控制器:
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) let destination = storyboard.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController navigationController?.pushViewController(destination, animated: true)
Segue公司:
首先你需要为你的segue设置一个标识符,如下所示:
performSegue(withIdentifier: "segue", sender: self) override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segue" { // Setup new view controller } }
编辑:更新为Swift 3.x
在故事板中,在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) }
如果使用,
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
所选行的值传递给另一个视图控制器的时间太晚。 你最好在func prepareForSegue中传递选中的行,首先声明一个全局variables来传递值给其他viewController
var globalVar:Int
在一个基于故事板的应用程序中,您通常需要在导航之前做一些准备工作
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let selectedIndex = self.tableView.indexPathForCell(sender as! UITableViewCell) globalVar = selectedIndex!.row print("tableView prepareForSegue: " + String(globalVar)) }
对于其他用户来到这个问题,如果你有一个UITableViewController
的静态单元格,你可以控制从单元格拖到新的视图控制器。
如果您不需要将任何数据传递到下一个View Controller,也可以在dynamic单元上执行此操作。 但是,如果您确实需要传递数据,那么您应该从Table View的视图控制器本身而不是单元格创buildSegue 。 然后以编程方式调用segue。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: "mySegueIdentifier", sender: self) }