我有两个 View Controller ,AbcViewController
和 XyzViewController
。两个 Controller 的行为相似。每个都有一个“添加”按钮,可分别打开 AddNewAbcViewController
和 AddNewXyzViewController
。
在 AddNewAbcViewController
上,当点击“提交”按钮时,它会执行必要的操作并关闭,将其带回 AbcViewController
。我在这里使用委托(delegate),其中 AbcViewController
关闭 AddNewAbcViewController
。这行得通。
现在我想对 XyzViewController
和 AddNewXyzViewController
执行相同的操作,但它不起作用。 AddNewXyzViewController
中调用btnSubmit时,并没有进入XyzViewController
的dimiss方法。我已经多次扫描我的代码,但没有发现任何未添加的额外内容。我什至在 XyzViewController
和 AddNewXyzViewController
中给出了不同的关闭方法名称,但这也不起作用。我错过了什么?
这是我的 AbcViewController
和 AddAbcViewController
片段。 Xyz 的代码是相同的:
类 AddNewAbcViewController.h
是
#import <Foundation/Foundation.h>
// protocol
@protocol AddNewAbcProtocol <NSObject>
-(void)dismiss;
@end
@interface AddNewAbcViewController : UIViewController<UITextViewDelegate>
@property(nonatomic, weak)id<AddNewAbcProtocol> delegate;
@end
类 AddNewAbcViewController.m
是
@interface AddNewAbcViewController() <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
...
@end
@implementation AddNewAbcViewController
...
- (IBAction)btnSubmit:(id)sender
{
[self.delegate dismiss];
}
@end
类 AbcViewController.h
是
#import <Foundation/Foundation.h>
#import "AddNewAbcViewController.h"
@interface AbcViewController : UIViewController<AddNewAbcProtocol, UISplitViewControllerDelegate>
...
@end
类 AbcViewController.m
是
@implementation AbcViewController
-(void)dismiss
{
NSLog(@"delegated to dismiss()");
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
最佳答案
正如大家所解释的,基本上你忘记了一行代码,如“.delegate = self”。
这是一个方便的初学者介绍给代表。
关于iOS - 代表不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26524815/