我有两个 View Controller
View Controller A
View Controller B
我在 View Controller A
中有一个表格 View ,列出了四种声音。当用户选择其中一种声音时,应将View Controller B
中的一个按钮编程为播放该声音。
我一直在使用 prepareForSeque
和 didSelectRowAtIndexPath
,但似乎无法让其中任何一个正常工作。
最好的方法是什么?
最佳答案
您必须在 didSelectRowAtIndexPath:
中跟踪选定的 indexPath。一种简单的方法是创建一个属性:
@property (strong, nonatomic) NSIndexPath *selectedIndexPath;
然后将选定的 indexPath 存储在该属性中,之后调用 performSegueWithIdentifier:sender:
方法:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedIndexPath = indexPath;
[self performSegueWithIdentifier:@"SEGUE_ID" sender:nil];
}
在 prepareForSegue:
中从声音数组中获取选定的声音:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"SEGUE_ID"])
{
ViewControllerB *controller = segue.destinationViewController.
controller.selectedSound = self.sounds[self.selectedIndexPath.row];
}
}
这是为了防止数组的名称是sounds
。您必须在 View Controller B 中创建一个属性来存储通过 segue 传递的声音。使用名称 SEGUE_ID
命名场景之间的转场。显然,您必须根据您的需求调整代码,我假设您的数组充满了引用声音名称的 NSString 对象。因此,最后一段代码中的属性 selectedSound
必须是 NSString。正如我所说,这取决于声音数组的结构。
编辑:根据@jlehr注释,通过删除 View Controller A中的属性,行self.selectedIndexPath = indexPath
和使用以下代码获取选定的indexPath:
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
ViewControllerB *controller = segue.destinationViewController.
controller.selectedSound = self.sounds[indexPath.row];
关于ios - 根据 TableView 选择将功能分配给第二个 View Controller 中的 IOS 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25473446/