ios - XCode 5.1.1 iOS 7.1 将数据发送到任一先前的 Controller

标签 ios objective-c back

<分区>

我有 2 个 View Controller ,A 和 B。当我单击按钮时,它们会将我带到 C - 一个带有自己的 View Controller 的 TableView 。 C 有一个项目列表,当您单击其中一个项目时,它将带您返回到上一个 Controller 。我正在使用此代码返回 didSelectRowAtIndexPath:

[self.navigationController popViewControllerAnimated:NO];

我的问题是:一旦弹出 C,如何以编程方式将数据发送回 A 或 B?

我环顾四周,但函数prepareForSegue没有在弹出时被调用 - 我使用了NSLog,但返回时没有打印任何内容。

最佳答案

你必须创建自定义委托(delegate)

在 CViewController.h 中

@protocol SecondViewControllerDelegate <NSObject>

@required
- (void)dataFromController:(NSString *)data;

@end

@interface CViewController : UIViewController

@property (nonatomic, weak) id<SecondViewControllerDelegate> delegate;

@end

在 CViewController.m 中

- (IBAction)btnBackAction:(id)sender {

    if([_delegate respondsToSelector:@selector(dataFromController:)])
    {
        [_delegate dataFromController:@"Data Received"];
    }

    [self.navigationController popViewControllerAnimated:YES];
}

在 A 或 BViewController 中(你想从 C 返回的地方)

// not forget to import CViewController.h
@interface A OR BViewController : UIViewController<SecondViewControllerDelegate>

现在在 A 或 BViewController.m 中

// when you go to CViewController from A Oor B then you have to pass delegate like  
CView.delegate = self;

- (void)dataFromController:(NSString *)data
{
    // this method invokes when you come back from CViewController

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 250, 50)];
    label.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth|
    UIViewAutoresizingFlexibleBottomMargin;
    label.textAlignment = NSTextAlignmentCenter;
    label.text = [NSString stringWithFormat:@"Your data: %@", data]; 
    [self.view addSubview:label];    
}  

关于ios - XCode 5.1.1 iOS 7.1 将数据发送到任一先前的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25375261/

上一篇:当应用程序从非事件状态变为非事件状态时调用的 iOS Controller 方法

下一篇:ios - ios项目使用unity3d的最佳实践

相关文章:

android - 我在退出 React Native 应用程序时遇到问题

ios - Firebase 移除观察者

ios - 当我的应用程序在 iPad 上运行时屏幕始终亮着

ios - 如何清除 WKWebView 的 WKBackForwardList?

javascript - 使用 pushState 后浏览器中的后退按钮无法正常工作(在 Chrome 中)

ios - UIWebView 在 iOS 中加载 HTML 后不会返回

Javascript : go back with new parameters

ios - 在 popover segues 中 Anchor 和 Passthrough 有什么用?

ios - GCD 混淆了滚动 TableView 上的数据

objective-c - 如何将 objective-c 中的 NSDictionary 转换为 Swift?