0

我在故事板中有两个场景。由于我不允许上传图片(新用户),我们称它们为场景 1 和场景 2。

Scene 1: UITableViewCell with a UILabel, when this cell is selected, it takes you to Scene 2.
Scene 2: Provides users options to select in UITableView. 一旦选择了一个选项,它就会在选定的 UITableViewCell 旁边放置一个复选标记。

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

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

4

1 回答 1

1

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

一般来说:

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

作为一个例子:

场景二界面

@class LabelSelectionTableViewController

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

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

场景二实现

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

场景一实现

- (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];
}
于 2012-12-31T16:31:25.397 回答