【发布时间】:2016-05-09 04:26:18
【问题描述】:
我在UINavigationController 中嵌入了两个UIViewController。第一个视图控制器的源代码如下:
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 最常见的委托错误:忘记设置委托
-
另外,方法应该永远以大写字母开头。
标签: ios objective-c cocoa-touch delegates uistoryboard