問題描述
如果我通過 Storyboard 創(chuàng)建一個(gè) UIImageView
并將其作為 @property
添加到 ViewController.h
中,我可以訪問該 UIImageView
從 ViewController.m
中的任何位置通過 [self UIImageView]
或 self.UIImageView
.
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
.
但是如果我從 viewDidLoad
以編程方式創(chuàng)建 UIImageView
,如下所示,我似乎無法從 viewDidLoad
外部訪問它.
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;
}
所以稍后如果我想修改從 viewDidLoad
創(chuàng)建的任何一個(gè) UIImageView
中顯示的圖像,我似乎無法訪問它.有誰知道我做錯(cuò)了什么?
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?
推薦答案
你需要在你的頭文件中創(chuàng)建你的 UIImageView,然后它就可以在視圖的其余部分中使用.不過,您需要將其添加到 viewDidLoad 中的視圖中.
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 ....
這篇關(guān)于如果以編程方式創(chuàng)建,則無法訪問 UIImageView的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!