使用委托设计模式允许两个对象相互通信(Apple 参考)。
一般来说:
- 在场景 2 中创建一个名为委托的属性。
- 在场景 2 中创建一个协议,定义场景 2 委托必须定义的方法。
- 在场景 1 到场景 2 的转场之前,将场景 1 设置为场景 2 的代理。
- 当在场景 2 中选择了一个单元格时,向场景 2 的代理发送消息以通知代理选择。
- 允许代理处理选择并在选择完成后关闭场景 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];
}