[英]Assigning function to IOS button in 2nd view controller based on Table View selection
I have two view controllers 我有两个视图控制器
View Controller A
View Controller B
I have a Table View in View Controller A
that lists out four sounds. 我在View Controller A
中有一个Table View,列出了四种声音。 When a user selects one of the sounds, a button in View Controller B
should be programmed to play that sound. 当用户选择一种声音时,应将View Controller B
的按钮编程为播放该声音。
I have been playing around with prepareForSeque
and didSelectRowAtIndexPath
and can't seem to get either one to work correctly. 我一直在和prepareForSeque
和didSelectRowAtIndexPath
玩耍,似乎无法使其中任何一个正常工作。
What is the best way to do this? 做这个的最好方式是什么?
You have to keep track of the selected indexPath in didSelectRowAtIndexPath:
. 您必须在didSelectRowAtIndexPath:
跟踪选定的indexPath。 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: 然后将所选的indexPath存储在该属性中,然后,调用performSegueWithIdentifier:sender:
方法:
- (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: 在prepareForSegue:
从sounds数组获取选定的声音:
- (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
. 在这种情况下,数组的名称是sounds
。 You have to create a property in the view controller B to store the sound passed through the segue. 您必须在视图控制器B中创建一个属性,以存储通过segue传递的声音。 Name a segue between the scenes with the name SEGUE_ID
. 使用名称SEGUE_ID
在场景之间命名一个segue。 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. 很明显,您必须根据需要调整代码,我假设您的数组中充满了NSString对象,这些对象引用了声音的名称。 So, the property selectedSound
in the last chunk of code have to be an NSString. 因此,最后一块代码中的selectedSound
属性必须是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: 编辑:根据@jlehr注释,通过删除视图控制器A中的属性self.selectedIndexPath = indexPath
并使用以下self.selectedIndexPath = indexPath
获取所选的indexPath,可以使代码更简洁:
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
ViewControllerB *controller = segue.destinationViewController.
controller.selectedSound = self.sounds[indexPath.row];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.