ios - Storyboard两个场景。将场景 2 中的 UITableViewCell 中的文本获取到场景 1 中的 UILabel

标签 ios uitableview storyboard scene

我的 Storyboard中有两个场景。由于我不允许上传图像(新用户),所以我们将它们称为场景 1 和场景 2。

场景 1:带有 UILabel 的 UITableViewCell,选择此单元格时,将带您到场景 2。
场景2:为用户提供在UITableView中选择的选项。一旦选择了一个选项,它就会在所选的 UITableViewCell 旁边放置一个复选标记。

当您单击场景 2 上的“保存”按钮时,它会从场景 2 中选定的 UITableViewCell 中获取文本,并将用户带回场景 1,并使用场景 2 中的文本填充 UILabel,如何获取它?

我使用 Storyboard来创建 UITableViews。每个单元格都有它自己的类。谢谢。

最佳答案

使用委托(delegate)设计模式允许两个对象相互通信 ( Apple reference )。

一般来说:

  1. 在场景 2 中创建一个名为 delegate 的属性。
  2. 在场景 2 中创建一个协议(protocol),定义场景 2 委托(delegate)必须定义的方法。
  3. 在从场景 1 到场景 2 的转场之前,将场景 1 设置为场景 2 的委托(delegate)。
  4. 当在场景 2 中选择某个单元格时,向场景 2 的代理发送一条消息,以通知该选择。
  5. 允许代理处理选择并在做出选择后关闭场景 2。

举个例子:

场景2界面

@class LabelSelectionTableViewController

@protocol LabelSelectionTableViewControllerDelegate
  - (void)labelSelectionTableViewController:(LabelSelectionTableViewController *)labelSelectionTableViewController didSelectOption:(NSString *)option;
@end

@interface LabelSelectionTableViewController : UITableViewController
  @property (nonatomic, strong) id <LabelSelectionTableViewControllerDelegate> delegate;
@end

场景2实现

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];   
  [self.delegate labelSelectionTableViewController:self didSelectOption:cell.textLabel.text];
}

场景1实现

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
  if ([segue.destinationViewController isKindOfClass:[LabelSelectionTableViewController class]] == YES)
  {
    ((LabelSelectionTableViewController *)segue.destinationViewController).delegate = self;
  }
}

// a selection was made in scene 2
- (void)labelSelectionTableViewController:(LabelSelectionTableViewController *)labelSelectionTableViewController didSelectOption:(NSString *)option
{
  // update the model based on the option selected, if any    
  [self dismissViewControllerAnimated:YES completion:nil];
}

关于ios - Storyboard两个场景。将场景 2 中的 UITableViewCell 中的文本获取到场景 1 中的 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14103720/

相关文章:

ios - 如何在单元格中设置 UILabel 相对于图像的位置

ios - UITableView单元格滚动时UIImageView随机显示

ios - 使用核心数据时在 UITableView 的顶部添加一个新行

ios - UIStoryboardSegue 动画子类中的属性

iphone - 如何在 xcode 4.3 lion 中查找将调用函数而不是搜索工具的位置

ios - 带有声音/音频的 NSMutableAttributedString

ios - 布局相对于边距警告 XCode 6 但没有约束

ios - 在 Storyboard 中的单个 ViewController 上隐藏状态栏

ios - 以秒、分钟、小时为单位的耗时

ios - 尽管在 Controller 中设置 tabbar.hidden = NO,TabBar 仍然隐藏