![](/img/trans.png)
[英]Pass data from Modal view to Parent view using delegates (with a segue in storyboard)
[英]Pass data in modal segue in storyboard?
我真正的問題是我想通過模態segue將數據從childViewController傳遞到storyboard中的parentViewController。
碼
parentViewController.h
@property (strong, nonatomic)NSMutableArray *address;
childViewController.m
parentViewController *parent=(parentViewController *)self.presentingViewController;
post.address=@"Hello World";
這個代碼拋出異常就好了
因未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:' - [MainTabbarViewController setAddress:]:無法識別的選擇器發送到實例0x7fa070e6b910'
故事板結構
TabbarController-> NavigationController-> parentViewController-> childViewController
先感謝您。
正確的方法是使用委托
在ChildViewController.h
@protocol ChildDelegate
- (void)postAddress:(NSString *)address;
@end
@interface ChildViewController
@property (nonAtomic, assign) id<ChildDelegate> delegate;
@end
在ChildViewController.m
[self.delegate postAddress:address];
在ParentViewController.h
@interface ParentViewController <ChildDelegate>
@end
在ParentViewController.m
// presenting childViewController
- (void)presentChildViewController {
ChildViewController *childViewController = [[ChildViewController alloc]init];
childViewController.delegate = self;
[self presentViewController:childViewController animated:YES completion:nil];
}
// delegate method
- (void)postAddress:(NSString *)address{
// add you code here
}
您無法像這樣將數據傳回父視圖控制器。 授權是實現這一目標的最佳方式。 請查看以下鏈接,詳細說明。
沒有辦法獲得創建你的segue的引用。 您可以在目標控制器中創建一個屬性(在我的示例中為sourceVC),並在prepareForSegue方法(在源視圖控制器中)中為self指定self:
[(ChildViewController *)segue.destinationViewController sourceVC] = self;
無論如何,我認為使用代表是一個更好的解決方案。
*在ChildViewController.h *
@protocol ChildDelegate <NSObject>
- (void)postAddress:(NSString*)ad;
@end
@interface ChildViewController : UIViewController
@property (weak, nonatomic) id <ChildDelegate> delegate;
@end
*在ParentViewController.h *
@interface ParentViewController : UIViewController <ChildDelegate>
@end
*在ParentViewController.m *
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
ChildViewController *vc = [segue destinationViewController];
vc.delegate = self;
}
*在ChildViewController.m *
- (void)changeAddress:(NSString*)ad
{
if ([self.delegate respondsToSelector:@selector(postAddress:)])
{
// Tell the delegate something.
[self.delegate postAddress:@"New Address"];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.