在此示例中,我有第二个视图控制器将自己呈现为模态:
在第二个视图控制器 h 文件中:
@protocol SecondViewControllerDelegate <NSObject>
- (void)addItemViewController:(id)controller didFinishEnteringItem:(NSString *)item;
@end
@interface SecondPageViewController : UIViewController <UITextViewDelegate>
{
NSString *previouslyTypedInformation;
}
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (nonatomic) NSString *previouslyTypedInformation;
@property (nonatomic, weak) id <SecondViewControllerDelegate> delegate;
在第二个视图控制器 m 文件中,确保合成属性并添加,然后添加:
- (IBAction)done:(id)sender
{
NSString *itemToPassBack = self.textView.text;
NSLog(@"returning: %@",itemToPassBack);
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];
//dismiss modal view controller here
}
然后在第一个视图控制器 h 文件中将其设置为委托:
@interface FirstPageViewController: UIViewController <SecondViewControllerDelegate>
@property (nonatomic) NSString *returnedItem;
然后在第一个视图控制器的m文件中合成并添加方法:
- (void)addItemViewController:(SecondPageViewController *)controller didFinishEnteringItem: (NSString *)item
{
//using delegate method, get data back from second page view controller and set it to property declared in here
NSLog(@"This was returned from secondPageViewController: %@",item);
self.returnedItem=item;
//add item to array here and call reload
}
现在你有了返回的文本!您可以在第一个视图控制器的 viewDidLoad 中将字符串添加到数组中并调用
[self.tableView reloadData];
它应该可以工作。