如何正确设置值到实例化的View Controller的控件?

时间:2016-12-06 02:27:02

标签: ios objective-c

我有一个类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:正确初始化对象的控件?

1 个答案:

答案 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;
}