在一个导航控制器中有两个视图控制器:
PhoneNumbersTVC
>保存NewPhoneNumberTVC
添加的电话号码列表NewPhoneNumberTVC
>电话号码添加控制器
当我点击取消NewPhoneNumberTVC
时,我喜欢用下面的委托返回PhoneNumbersTVC
。
PhoneNumbersTVC.h
#import <UIKit/UIKit.h>
#import "NewPhoneNumberTVC.h"
@interface PhoneNumbersTVC : UITableViewController <NewPhoneNumberTVCDelegate>
@end
PhoneNumbersTVC.m
- (void)saveBtnWasTappedOnNewPhoneNumberTVC:(NewPhoneNumberTVC *)newPhoneNumberTVC
{
NSLog(@"saveBtnWasTappedOnNewPhoneNumberTVC");
[newPhoneNumberTVC.navigationController popViewControllerAnimated:YES];
}
- (void)cancelBtnWasTappedOnNewPhoneNumberTVC:(NewPhoneNumberTVC *)newPhoneNumberTVC
{
NSLog(@"cancelBtnWasTappedOnNewPhoneNumberTVC");
[newPhoneNumberTVC.navigationController popViewControllerAnimated:YES];
}
NewPhoneNumberTVC.h
#import <UIKit/UIKit.h>
@class NewPhoneNumberTVC;
@protocol NewPhoneNumberTVCDelegate <NSObject>
- (void)saveBtnWasTappedOnNewPhoneNumberTVC:(NewPhoneNumberTVC *)newPhoneNumberTVC;
- (void)cancelBtnWasTappedOnNewPhoneNumberTVC:(NewPhoneNumberTVC *)newPhoneNumberTVC;
@end
@interface NewPhoneNumberTVC : UITableViewController
@property (weak, nonatomic) id <NewPhoneNumberTVCDelegate> delegate;
@property (strong, nonatomic) NSManagedObjectContext *managedOC;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
- (IBAction)saveBtnTapped:(UIBarButtonItem *)sender;
- (IBAction)cancelBtnTapped:(UIBarButtonItem *)sender;
@end
NewPhoneNumberTVC.m
- (IBAction)cancelBtnTapped:(UIBarButtonItem *)sender
{
NSLog(@"cancelBtnTapped");
self.phoneNumberTextField.text = @"";
self.phoneKindTextField.text = @"";
[self.delegate cancelBtnWasTappedOnNewPhoneNumberTVC:self];
}
当我在NewPhoneNumberTVC
上点击取消时,我看到上面的方法cancelBtnTapped
触发,但delegation
不起作用,没有method
在PhoneNumbersTVC
中执行。视图没有消失,我没有看到:cancelBtnWasTappedOnNewPhoneNumberTVC
在console
上
如果你想要这个方法cancelBtnWasTappedOnNewPhoneNumberTVC:
被调用,你肯定需要将你的NewPhoneNumberTVC
对象的委托设置为PhoneNumbersTVC
对象。例如,PhoneNumbersTVC中应该存在一些代码。m :
NewPhoneNumberTVC *myNewPhoneNumberTVC = [[NewPhoneNumberTVC alloc] init];
myNewPhoneNumberTVC.delegate = self;
您可以按照以下方式进行日志记录,以验证委托是否成功设置"
NewPhoneNumberTVC.m
- (IBAction)cancelBtnTapped:(UIBarButtonItem *)sender
{
NSLog(@"cancelBtnTapped");
self.phoneNumberTextField.text = @"";
self.phoneKindTextField.text = @"";
NSLog(@"self.delegate :%@",self.delegate);
[self.delegate cancelBtnWasTappedOnNewPhoneNumberTVC:self];
}