Swift: Pass UITableViewCell label to new ViewController

后端 未结 4 1318
难免孤独
难免孤独 2020-12-01 03:23

I have a UITableView that populates Cells with data based on a JSON call. like so:

var items = [\"Loading...\"]
var indexValue = 0

// Here is SwiftyJSON co         


        
4条回答
  •  鱼传尺愫
    2020-12-01 03:30

    Passing data between two view controllers depends on how view controllers are linked to each other. If they are linked with segue you will need to use performSegueWithIdentifier method and override prepareForSegue method

    var valueToPass:String!
    
    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)!")
    
        // Get Cell Label
        let indexPath = tableView.indexPathForSelectedRow();
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
    
        valueToPass = currentCell.textLabel.text
        performSegueWithIdentifier("yourSegueIdentifer", sender: self)
    
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
        if (segue.identifier == "yourSegueIdentifer") {
    
            // initialize new view controller and cast it as your view controller
            var viewController = segue.destinationViewController as AnotherViewController
            // your new view controller should have property that will store passed value
            viewController.passedValue = valueToPass
        }
    
    }
    

    If your view controller are not linked with segue then you can pass values directly from your tableView function

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)!")
    
        // Get Cell Label
        let indexPath = tableView.indexPathForSelectedRow();
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
        let storyboard = UIStoryboard(name: "YourStoryBoardFileName", bundle: nil)
        var viewController = storyboard.instantiateViewControllerWithIdentifier("viewControllerIdentifer") as AnotherViewController
        viewController.passedValue = currentCell.textLabel.text
        self.presentViewController(viewContoller, animated: true , completion: nil) 
    }
    

提交回复
热议问题