This question already has answers here:
Passing Data between View Controllers
                                
                                    (43个答案)
                                
                        
                                5年前关闭。
            
                    
我有2个视图控制器,A和B。单击按钮时,这些按钮将我带到C-具有其自己的视图控制器的表视图。 C有一个项目列表,当您单击其中的一项时,它将带您回到上一个控制器。我正在使用以下代码返回didSelectRowAtIndexPath:

[self.navigationController popViewControllerAnimated:NO];


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

我环顾四周,但是函数pop并没有在弹出窗口中调用-我用过NSLog,返回时什么也没打印。

最佳答案

您必须创建自定义委托

在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];
}

07-27 22:23