所以我的目标是当选择单元格以在单元格内获取文本标签并将其打印到新的视图控制器UILabel中时。
我已经将其设置为选择单元格时将其推送到新视图控制器的位置。 我只是不知道如何让它将单元格文本标签打印到新视图控制器的UILabel中。
这是我的表格视图代码,但我应该写什么才能将单元格文本标签检索到我的新视图控制器中?
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)
}
据我在您的问题中看到,您正在尝试将数据从一个控制器传递到另一个控制器。在您的情况下,您可以在像以前一样点击单元格时使用 didSelectRowAtIndexPath
方法,只需将值设置为secondViewController
中的UILabel
,或者您可以将单元格的推送 segue 设置为下一个控制器,并在prepareForSegue
传递所需的数据。
案例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)
}
案例2:
在情节提要中设置续集后:
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
设置值。
我希望这对你有所帮助。