问题
I am having a problem accessing data sent from a tableViewController to a viewController.
The first file, tableView Controller is using the following to find the selected row and pass data via a segue:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Get the row data for the selected row
var name = self.names[indexPath.row]
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell)
if segue.identifier == "PictureSegue"{
let vc = segue.destinationViewController as pictureViewController
vc.recvData = name
}
}
}
The second file (viewController) is trying to read the data and open an alert. The alert keeps coming up null. Why is it not receiving the data?
class pictureViewController: UIViewController {
var recvData:String!
override func viewDidLoad() {
super.viewDidLoad()
if recvData != nil
{
if (recvData == "Apapne")
{
var alert: UIAlertView = UIAlertView()
alert.title = recvData
alert.message = recvData
alert.addButtonWithTitle("Ok")
alert.show()
}
}
else
{
var alert: UIAlertView = UIAlertView()
alert.title = "no"
alert.message = "stuff"
alert.addButtonWithTitle("Ok")
alert.show()
}
}
}
Thank you
回答1:
Don't access the property in viewDidLoad - it won't be set at that point. Access it in viewWillAppear
回答2:
The problem is the prepareForSegue method . You have to override it. In your case you're just defining a function inside the tableView didSelectRowAtIndexPath method which is named prepareForSegue, but you should insert an override method ,instead of your internal function :
override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) {
// do preparations
}
来源:https://stackoverflow.com/questions/26903383/swift-segue-not-passing-data-from-tableview