我有一个类ErrorMessageViewController:
// ErrorMessageViewController.h
@interface ErrorMessageViewController: UIViewController
@property (nonatomic, strong) IBOutlet UILabel* messageTitle;
@property (nonatomic, strong) IBOutlet UILabel* messageContent;
@end
// ErrorMessageViewController.m
@implementation ErrorMessage
@synthesize messageTitle, messageContent;
@end
我实例化这个视图控制器:
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ErrorMessageViewController * errorMessage = (ErrorMessageViewController *) [storyboard instantiateViewControllerWithIdentifier:@"ErrorMessage"];
[[errorMessage messageTitle] setText:@"Error"];
[[errorMessage messageContent] setText:@"Duplicate ID"];
[[self navigationController] pushViewController:errorMessage animated:YES];
但是出现的View Controller的messageTitle和messageContent UILabel是空的。我仔细检查并确保UILabel
已连接到故事板的UILabel
。
为什么会这样?如何从instantiateViewControllerWithIdentifier:
正确初始化对象的控件?
答案 0 :(得分:2)
// ErrorMessageViewController.h
@interface ErrorMessageViewController: UIViewController
@property (nonatomic, strong) IBOutlet UILabel* messageTitle;
@property (nonatomic, strong) IBOutlet UILabel* messageContent;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *msg;
@end
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ErrorMessageViewController * errorMessage = (ErrorMessageViewController *) [storyboard instantiateViewControllerWithIdentifier:@"ErrorMessage"];
errorMessage.title = @"Error";
errorMessage.msg = @"Duplicate ID";
[[self navigationController] pushViewController:errorMessage animated:YES];
在'viewDidLoad'
中- (void)viewDidLoad {
[super viewDidLoad];
messageTitle.text = title;
messageContent.text = msg;
}