为什么我的委托方法没有在故事板中调用?

时间:2016-01-31 19:27:36

标签: ios objective-c cocoa-touch delegates uistoryboard

我在UIViewController中嵌入了两个UINavigationController。第一个视图控制器具有以下源代码:

ViewController.h:

#import <UIKit/UIKit.h>
#import "ViewController_2.h"

@interface ViewController : UIViewController <HanselDelegate>

@property (strong, nonatomic) IBOutlet UILabel *TestLabel;

- (IBAction)ButtonClick:(id)sender;

@end

ViewController.m:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
     [super viewDidLoad];
     // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
     [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
}

- (IBAction)ButtonClick:(id)sender {
     NSLog(@"To call the second UIViewController...");
     [self performSegueWithIdentifier:@"idCallSecond" sender:self];
}

-(void)SetFirstLabel {
     NSLog(@"To run the delegate method...");
     _TestLabel.text = @"Hello from the second...";
}
@end

第二个控制器具有以下代码:

ViewController2.h:

#import <UIKit/UIKit.h>

@protocol HanselDelegate <NSObject>

-(void)SetFirstLabel;

@end

@interface ViewController_2 : UIViewController

@property (nonatomic, weak)id<HanselDelegate> delegate;

- (IBAction)Button2Click:(id)sender;
@end

ViewController2.m:

#import "ViewController_2.h"

@interface ViewController_2 ()

@end

@implementation ViewController_2

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)Button2Click:(id)sender {
    if ([self.delegate respondsToSelector:@selector(SetFirstLabel)]) {
        NSLog(@"To call the delegate method");
        [self.delegate SetFirstLabel];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
@end

如果我按下ViewController2中的按钮,方法SetFirstLabel就不会被调用。为什么会这样?我忘记了什么吗?

1 个答案:

答案 0 :(得分:3)

您忘记在ViewController.m中设置委托

在ViewController.m中设置它

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"idCallSecond"]) {
        ViewController_2 * vc2 = [segue destinationViewController];
        vc2.delegate = self;
    }
}