swift segue not passing data from tableview

依然范特西╮ 提交于 2019-12-11 07:25:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!