简体   繁体   中英

Assigning function to IOS button in 2nd view controller based on Table View selection

I have two view controllers

  1. View Controller A

  2. View Controller B

I have a Table View in View Controller A that lists out four sounds. When a user selects one of the sounds, a button in View Controller B should be programmed to play that sound.

I have been playing around with prepareForSeque and didSelectRowAtIndexPath and can't seem to get either one to work correctly.

What is the best way to do this?

You have to keep track of the selected indexPath in didSelectRowAtIndexPath: . A simple way is to create a property:

@property (strong, nonatomic) NSIndexPath *selectedIndexPath;

And then store the selected indexPath in that property, after that, call to the performSegueWithIdentifier:sender: method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     self.selectedIndexPath = indexPath;
     [self performSegueWithIdentifier:@"SEGUE_ID" sender:nil];
}

In prepareForSegue: get the selected sound form the sounds array:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"SEGUE_ID"])
    {
        ViewControllerB *controller = segue.destinationViewController.
        controller.selectedSound = self.sounds[self.selectedIndexPath.row];
    }
}

That is in case that the name of the array is sounds . You have to create a property in the view controller B to store the sound passed through the segue. Name a segue between the scenes with the name SEGUE_ID . It is obvious that you have to adapt the code to your needs, I'm assuming your array is full of NSString objects referencing the names of your sounds. So, the property selectedSound in the last chunk of code have to be an NSString. As I said, it depends of the structure of your array of sounds.

Edit: According to the @jlehr comment, the code can be more concise by removing the property in the View Controller A, the line self.selectedIndexPath = indexPath and obtaining the selected indexPath with the following instead:

NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
ViewControllerB *controller = segue.destinationViewController.
controller.selectedSound = self.sounds[indexPath.row];

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