Can#39;t access UIImageView if created programmatically(如果以编程方式创建,则无法访问 UIImageView)
问题描述
如果我通过 Storyboard 创建一个 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
以编程方式创建 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
创建的任何一个 UIImageView
中显示的图像,我似乎无法访问它.有谁知道我做错了什么?
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?
推荐答案
你需要在你的头文件中创建你的 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 ....
这篇关于如果以编程方式创建,则无法访问 UIImageView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果以编程方式创建,则无法访问 UIImageView
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01