Search code examples
iosswiftuitableviewswift2uistoryboardsegue

working with cell on tableview using swift 2


I am developing a app using Swift 2. In my app I am parsing JSON data to a table view. When I tap a cell it successfully moves to another view controller but I am unable to fetch the json data.

This is the code in my view controller:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath){
    var cell = self.TableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! CustomTableCell
    let strbookdetail : NSString=arrDict[indexPath.row] .valueForKey("booking_detail") as! NSString
    let strdrop : NSString=arrDict[indexPath.row] .valueForKey("drop_address") as! NSString
    cell.Bookdetail.text=strbookdetail as String
    cell.Dropaddress.text=strdrop as String
    return cell as CustomTableCell

}

//It helps to parse JSON  data to table view.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    TableView.deselectRowAtIndexPath(indexPath, animated: true)
    let tripcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("UpcomingController") as! Secondcontroller
    navigationController?.pushViewController(tripcontroller, animated: true)

}

When tapping on the cell it helps to move to other view controller SecondController

In my SecondController I have two UILabels. In those labels I want to show data i.e strbookdetail and strdrop

How can I pass a reference between the two view controllers?


Solution

  • It is easy to do using property pass data:

    In 2th vc:

    var dataFromBeforeVC:[String:String] = [String:String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    
        initData ()
    
    }
    
    func initData()  {
    
        // set data  strbookdetail and strdrop to labelOne & labelTwo
    
        labelOne.text = dataFromBeforeVC["strdrop"]
        labelTwo.text = dataFromBeforeVC["strbookdetail"]
    
    
    }
    

    In 1th vc:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
        TableView.deselectRowAtIndexPath(indexPath, animated: true)
        let tripcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("UpcomingController") as! Secondcontroller
    
        let cell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
    
        let strbookdetail : NSString=arrDict[indexPath.row] .valueForKey("booking_detail") as! NSString
        let strdrop : NSString=arrDict[indexPath.row] .valueForKey("drop_address") as! NSString
        tripcontroller.dataFromBeforeVC = [
            "strdrop":strbookdetail,
            "strdrop":strbookdetail
        ]
    
        self.navigationController?.pushViewController(tripcontroller, animated: true)
    }