因此,我的目标是选择单元格以将文本标签选中在单元格内并在新的ViewControllers Uilabel中打印。
我已经将它设置为当单元格被选中时它被推送到新的 View Controller 。我只是不知道如何让它将单元格 textLabel 打印到新 ViewController 的 UILabel 中。
这是我的 TableView 代码,但是我应该写什么来将单元格 textLabel 检索到我的新 ViewController 中?
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("showPostContent") as! showPostContent
print(currentCell.textLabel?.text)
self.navigationController?.pushViewController(secondViewController, animated: true)
}
最佳答案
据我所知,在您的问题中,您正在尝试将数据从一个 Controller 传递到另一个 Controller 。在您的情况下,您可以在像您一样点击单元格时使用 didSelectRowAtIndexPath
方法,只需将您的值设置为 secondViewController
中的 UILabel
或您可以为单元格设置推送 segue 到下一个 Controller ,并在 prepareForSegue
中传递您需要的数据。
Case 1:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("showPostContent") as! showPostContent
// this line call the loadView method to avoid the IBOutlet is not nil
let _ = secondViewController.view
// pass the data
secondViewController.NameOfYourUILabelOutlet.text = currentCell.textLabel?.text
print(currentCell.textLabel?.text)
self.navigationController?.pushViewController(secondViewController, animated: true)
}
Case 2:
在 Storyboard 中设置 segue 之后:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationViewController = segue.destinationViewController as! NameOfYourViewController
let _ = destinationViewController.view
guard let indexPath = self.tableView.indexPathForSelectedRow else { return }
let indexOfCellSelected = indexPath.row
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
destinationViewController.NameOfYourUILabelOutlet.text = cell.NameOfYourUILabelOutlet.text
}
如果您不想调用view
属性来实例化@IBOulet
,您可以创建一个属性为其设置值,然后在viewDidLoad
为里面的 @IBOulet
设置值。
希望对你有帮助
关于swift - 将 TableView 中的单元格文本打印到新的 viewController UILabel (swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36106059/