objective-c - 使用后退按钮将数据传递到 ViewController

标签 objective-c ios xcode

我在 ViewA 中有多个按钮。单击按钮时,它会重定向到 ViewB。在 ViewB 中,用户进行一些交互,然后在完成后单击返回按钮。如何运行方法并将参数从 ViewB 传递到 ViewA,然后继续在 ViewA 中工作?

强烈要求使用后退按钮,但我很想知道是否还有其他方法。

我的想法是从堆栈中获取 ViewA,当我完成 ViewB 时,只需调用它并重定向,但我不知道该怎么做。

谢谢。

最佳答案

您想在 ViewB 中定义一个委托(delegate)并在 ViewA 中实现它。在适当的时候(例如,当点击后退按钮时)ViewB 调用委托(delegate)方法,将值作为参数传递。

像这样:

ViewB.h

// Define a delegate protocol allowing 
@protocol ViewBDelegate

// Method of delegate called when user taps the 'back' button
-(void) backButtonSelected:(id) object;

@end


@interface ViewB : UIViewController

// property to hold a reference to the delegate
@property (weak)id<ViewBDelegate> delegate;

-(IBAction)backButtonSelected:(id)sender;

@end

ViewB.m:

@implementation ViewB

...

-(IBAction)backButtonSelected:(id)sender{
    NSObject *someObjectOrValue = nil;

    // Invoke the delegates backButtonSelected method, 
    // passing the value/object of interest
    [self.delegate backButtonSelected:someObjectOrValue];
}

@end

ViewA.h:

#import "ViewB.h"


//  The identifier in pointy brackets (e.g., <>) defines the protocol(s)
// ViewA implements
@interface ViewA : UIViewController <ViewBDelegate>

...

-(IBAction)someButtonSelected:(id)sender;

@end

ViewA.m:

-(IBAction) someButtonSelected:id @实现ViewA

...

// Called when user taps some button on ViewA (assumes it is "hooked up" 
// in the storyboard or IB
-(IBAction)someButtonSelected:(id)sender{

    // Create/get reference to ViewB.  May be an alloc/init, getting from storyboard, etc.
    ViewB *viewB = // ViewB initialization code

    // Set `ViewB`'s delegate property to this instance of `ViewA`
    viewB.delegate = self;
    ...
}

// The delegate method (defined in ViewB.h) this class implements
-(void)backButtonSelected:(id)object{
    // Use the object pass as appropriate
}

@end

关于objective-c - 使用后退按钮将数据传递到 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13534470/

相关文章:

ios - 导航栏按钮不起作用,因为它不是 xcode 中的初始场景

ios - UIDatePickerView 问题,因为更新到 ios 8

iphone - 它会影响 map 加载速度/性能吗? addAnnotation 与 addAnnotations

objective-c - 在类型 'myArray' 的对象上找不到属性 'MyVC *' Swift 到 Obj-C 传递数组错误

ios - AVAudioRecorder 不工作

ios - 找到离坐标最近的商店

iphone - reloadData 只刷新一行

ios - 将绝对 URL 更改为相对 URL 使用系统 API 快速而干净?

ios自动布局类似

ios - 添加 subview 不起作用