我不知道这是怎么回事。我正在尝试向当前视图添加一个子视图。我alloc
和initWithNibName
我的SecondViewController
并将其myImageView
参数设置为UIImageView
。问题在于,当添加subView时,未设置myImageView
。
这是代码:
- (void)viewDidLoad
{
[super viewDidLoad];
SecondViewController *secondView = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];
secondView.myImageView.image = [UIImage imageNamed:@"image1.png"];
[self.view addSubview secondView.view];
}
如果我通过Interface Builder将图像设置为
myImageView
,则它会正确显示在addSubview
上,但是如果如上所述设置属性,它将不起作用... UIImageView
插座已正确连接到IB。这是
SecondViewController
:@interface SecondViewController : UIViewController
{
}
@property(nonatomic,strong)IBOutlet UIImageView *myImageView;
@end
最佳答案
我相信您的问题是,当您调用secondView.myImageView.image = [UIImage imageNamed:@"image1.png"];
时,尚未设置myImageView出口。 initWithNibName:bundle:
的文档说:“您指定的nib文件不会立即加载。它是在第一次访问视图控制器的视图时加载的。”因此,您需要这样的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
SecondViewController *secondView = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];
// Force the nib to load, which subsequently sets the myImageView outlet
[secondView view];
secondView.myImageView.image = [UIImage imageNamed:@"image1.png"];
[self.view addSubview secondView.view];
}
但是,我不推荐这种方法。您实际上应该在SecondViewController的-viewDidLoad方法中设置myImageView插座的图像。那就是它的归属。
// SecondViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.myImageView.image = [UIImage imageNamed:@"image1.png"];
}
然后在另一个视图控制器的-viewDidLoad方法中,只需像以前一样将SecondViewController的视图添加为子视图:
- (void)viewDidLoad
{
[super viewDidLoad];
SecondViewController *secondVC = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self.view addSubview:secondVC.view];
}