添加UIView以使用UIImageView参数进行查看

时间:2012-08-01 18:19:14

标签: ios uiview uiimageview addsubview

我无法弄清楚这有什么问题。我正在尝试将子视图添加到当前视图中。我allocinitWithNibName我的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

2 个答案:

答案 0 :(得分:1)

我相信您的问题是,当您致电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];
}

答案 1 :(得分:0)

如果通过IB将其设置为myImageView,它将实例化myImageView。如果您使用上面的代码,myImageView就会被实例化。

您必须在SecondViewController viewDidLoad或initWithFrame中添加以下行:

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)]
secondView.myImageView = imageView;

[感谢H2CO3]