ios - 根据 TableView 选择将功能分配给第二个 View Controller 中的 IOS 按钮

标签 ios objective-c delegates

我有两个 View Controller

  1. View Controller A

  2. View Controller B

我在 View Controller A中有一个表格 View ,列出了四种声音。当用户选择其中一种声音时,应将View Controller B 中的一个按钮编程为播放该声音。

我一直在使用 prepareForSequedidSelectRowAtIndexPath ,但似乎无法让其中任何一个正常工作。

最好的方法是什么?

最佳答案

您必须在 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/

相关文章:

ios - 使用单个 iOS 设备测试 iCloud 同步

ios - 在不阻塞 UI 的情况下在 For 循环中添加延迟

objective-c - 尝试标记应用程序图标,但未获得用户标记应用程序的权限 : iOS 8 Xcode 6

objective-c - objective-c 两个整数的除法

design-patterns - 您是否在具有闭包/委托(delegate)/函数指针的编程语言中使用模板方法模式?

ios - 如何在 iOS Swift 中将 UIButton 操作从 View Controller 调用到另一个 View Controller ?

ios - 如何执行 fetch 请求以获取带有表达式描述的参数之和?

ios - NSString 子串检测

ios - 更改 UIViewController 的方向会影响另一个 UITableViewController 的边界

swift - 如何通过动画 UIView 将 UIImage 设置到 SWIFT 中的另一个 View Controller