简体   繁体   中英

passing an array from a table view to a view controller on xcode7 in swift

I've got a table view with X rows and i want that if I tap one of the rows it displays a view controller with a different value each. I know that i have to use prepareForSegue but i don't know how. I'll make an example: There's the table view with 4 rows. I tap the first row and it opens a view controller with a label that shows "1". I tap the second row and it opens a view controller with a label that shows "2". And so on. I don't want to create milions of view controllers, i'd like to have only one of them that changes every time.

You'll make me a big favor. Thanks

First you need to detect the user's selection.

This is done with the -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath function.

Once you have detected the selected row, you need to invoke the the next view controller. You can do this by instantiating the viewController you want to show using the storyboard: UIViewController* viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"Your VC identifier here"];

To pass information to another controller you can create a property and set it like any other object:

[viewController setCustomArray:@[]]

Finally you need to present the view controller:

[self presentViewController:viewController animated:YES completion:nil]

You need to add the following in your tableViewController class

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    text = indexPath.row
    performSegueWithIdentifier("YourSegue", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == "YourSegue" {
    let yourOtherVC = segue.destinationViewController as? SecondViewController
        yourOtherVC?.text = text
  }
}

In your SecondViewController class, add the following:

class SecondViewController: UITableViewController {

var text:String = ""
@IBOutlet weak var myLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    if text != nil {
        myLabel.text = text
    }
}

Hope this helps. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM