我在 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/