Passing data from a tableview to webview

2019-04-17 12:38发布

I am new of the swift3. So, please forgive me if you think it is easy question. Do not have a clear idea when searching internet or stack overflow with my situation, so I ask this question.

Goal: Passing data from a tableview to webview

Example: data 1,2,3... in the table, press 1, then jump into webview with value 1

Information:

  • In main.storyboard, looks like:
    main.storyboard
  • class oneViewController for a view controller with tableview

  • class twoViewController for a view controller with webview

In oneViewController, things are well set and select row at:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Array[indexPath.row]   //This value expected to pass
    //some code to execute passing data...
    //Also, jump into another view controller with webview
}  

In twoViewController, everything got ready:

 //let passData = some code to get the data....
 let URL = NSURL(string: "https://www.example.com?data=\(passData)")

 webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)

Finally, PHP can get the value

echo $_GET["data"];

Questions:

  1. How to set the relationship between tableview and webview in main.storyblard?

Connect view controller to anther view controller? Or connect Table view Cell to view controller? Or something else.....

  1. How to implement passing data in class oneViewController and twoViewController?

标签: ios swift3
2条回答
淡お忘
2楼-- · 2019-04-17 13:24

you can do three solutions :

1- send data in segue

2- forget the segue relation and call the new controller in didSelectRowAt, and set data like this :

let vc = UIStoryboard(name: "BarcodeScanner", bundle: nil).instantiateInitialViewController()! as! BarcodeScannerViewController
vc.passData = valueWantToSend
self.presentViewController(vc, animated: true, completion: nil)

3- use struct like this and you be able to use your data from any place in your project :

struct Variables 
{
   static var value = false
   static var passData = ""
}  

for exemple : Variables.passData=@"new value"

查看更多
ら.Afraid
3楼-- · 2019-04-17 13:39

Follow the below steps:-

Step 1: Below code will launch and pass the data in your TwoViewController. Please note that in your Main.Storyboard->TwoViewContoller, give the identifier as TwoViewController

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let storyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let twoVC:TwoViewController = storyBoard.instantiateViewController(withIdentifier: "TwoViewController") as! TwoViewController
    twoVC.passData = Array[indexPath.row]
    self.present(twoVC, animated: true, completion: nil)
}  

Step 2: In your TwoViewController class define a variable as below

var passData: String = ""
查看更多
登录 后发表回答