我有一个UITableView,它使用基于JSON调用的数据填充单元格。像这样:
var items = ["Loading..."] var indexValue = 0 // Here is SwiftyJSON code // for (index,item) in enumerate(json) { var indvItem = json[index]["Brand"]["Name"].stringValue self.items.insert(indvItem,atIndex: indexValue) indexValue++ } self.tableView.reloadData()
选择单元格后,如何获取标签,然后将其传递给另一个ViewController?
我设法得到:
func tableView(tableView: UITableView!,didSelectRowAtIndexPath indexPath: NSIndexPath!) { println("You selected cell #\(indexPath.row)!") // Get Cell Label let indexPath = tableView.indexPathForSelectedRow(); let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!; println(currentCell.textLabel.text) }
我只是不知道如何将它作为一个变量传递给下一个UIViewController。
谢谢
在两个视图控制器之间传递数据取决于视图控制器如何相互链接。如果它们与segue链接,则需要使用performSegueWithIdentifier方法并覆盖prepareForSegue方法
var valueToPass:String! func tableView(tableView: UITableView!,didSelectRowAtIndexPath indexPath: NSIndexPath!) { println("You selected cell #\(indexPath.row)!") // Get Cell Label let indexPath = tableView.indexPathForSelectedRow(); let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!; valueToPass = currentCell.textLabel.text performSegueWithIdentifier("yourSegueIdentifer",sender: self) } override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) { if (segue.identifier == "yourSegueIdentifer") { // initialize new view controller and cast it as your view controller var viewController = segue.destinationViewController as AnotherViewController // your new view controller should have property that will store passed value viewController.passedValue = valueToPass } }
如果您的视图控制器没有与segue链接,那么您可以直接从tableView函数传递值
func tableView(tableView: UITableView!,didSelectRowAtIndexPath indexPath: NSIndexPath!) { println("You selected cell #\(indexPath.row)!") // Get Cell Label let indexPath = tableView.indexPathForSelectedRow(); let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!; let storyboard = UIStoryboard(name: "YourStoryBoardFileName",bundle: nil) var viewController = storyboard.instantiateViewControllerWithIdentifier("viewControllerIdentifer") as AnotherViewController viewController.passedValue = currentCell.textLabel.text self.presentViewController(viewContoller,animated: true,completion: nil) }