我的 Storyboard中有两个场景。由于我不允许上传图像(新用户),所以我们将它们称为场景 1 和场景 2。
场景 1:带有 UILabel 的 UITableViewCell,选择此单元格时,将带您到场景 2。
场景2:为用户提供在UITableView中选择的选项。一旦选择了一个选项,它就会在所选的 UITableViewCell 旁边放置一个复选标记。
当您单击场景 2 上的“保存”按钮时,它会从场景 2 中选定的 UITableViewCell 中获取文本,并将用户带回场景 1,并使用场景 2 中的文本填充 UILabel,如何获取它?
我使用 Storyboard来创建 UITableViews。每个单元格都有它自己的类。谢谢。
最佳答案
使用委托(delegate)设计模式允许两个对象相互通信 ( Apple reference )。
一般来说:
- 在场景 2 中创建一个名为 delegate 的属性。
- 在场景 2 中创建一个协议(protocol),定义场景 2 委托(delegate)必须定义的方法。
- 在从场景 1 到场景 2 的转场之前,将场景 1 设置为场景 2 的委托(delegate)。
- 当在场景 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
场景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/