Can't access UIImageView if created programmat

2019-03-06 09:01发布

If I create a UIImageView via Storyboard and add it as a @property into a ViewController.h, I can access that UIImageView from anywhere in the ViewController.m via [self UIImageView] or self.UIImageView.

But If I create the UIImageView programmatically from viewDidLoad as you see below, I seem to lose the ability to access it from outside viewDidLoad.

UIImageView *prevImgView = [[UIImageView alloc] init];
UIImageView *currImgView = [[UIImageView alloc] init];
UIImageView *nextImgView = [[UIImageView alloc] init];

NSArray *imageViews = [NSArray arrayWithObjects:prevImgView, currImgView, nextImgView, nil];

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
[self.view addSubview: scrollView];

CGRect cRect = scrollView.bounds;
UIImageView *cView;

for (int i=0; i<imageViews.count; i++) {
    cView = [imageViews objectAtIndex:i];
    cView.frame = cRect;
    [scrollView addSubview:cView];
    cRect.origin.x += cRect.size.width;
}

So later on if I want to modify the image that is being displayed in any one of the UIImageView I've created from viewDidLoad, I can't seem to access it. Does anyone know what I'm doing wrong?

2条回答
唯我独甜
2楼-- · 2019-03-06 09:22

You would need to create your UIImageView in your header file and then it would be available throughout the rest of the view. You will need to add it to the view in viewDidLoad though.

         Header
         UIImageView *image;

         Main // ViewDidLoad
         image = [UIImageView alloc] .....
         [self.view addSubView image];


         Main Function .....
         [image setImage ....
查看更多
爷、活的狠高调
3楼-- · 2019-03-06 09:23

The answer AgnosticDev is trying to say here is to add an ivar to your view controller's .h file... e.g.:

@implementation YHLViewController : ViewController
{
    UIImageView * currImageView;
}

And then in your "viewDidLoad" method, you can allocate and initialize it via:

currImageView = [[UIImageView alloc] init];

and have access to it from anywhere else in your view controller.

查看更多
登录 后发表回答