UIImageView奇怪的图像属性问题

发布于 2024-10-16 10:28:27 字数 406 浏览 3 评论 0原文

我正在处理一个超级简单的任务,但不知何故引入了一些困难...

我想做的就是创建一个视图控制器并将其 UIImageView 的图像属性设置为某个图像。 当我尝试这样做时,我得到 nil =\

GenericViewController *genericViewController = [[GenericViewController alloc] init];
UIImage *image = [UIImage imageNamed:@"Camera.png"];
genericViewController.genericImageView.image = image;
NSLog(@"%@", genericViewController.genericImageView.image);

输出:(null)

I'm dealing with a super easy task that somehow introducing some difficulties...

All I'm trying to do is to create a view controller and set its UIImageView's image property to some image.
When I try to that, I get nil =\

GenericViewController *genericViewController = [[GenericViewController alloc] init];
UIImage *image = [UIImage imageNamed:@"Camera.png"];
genericViewController.genericImageView.image = image;
NSLog(@"%@", genericViewController.genericImageView.image);

Output: (null)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

临风闻羌笛 2024-10-23 10:28:27

我想象 genericImageView 是在笔尖或 -loadView 方法中设置的。然而,当您尝试访问图像视图时,VC 的视图尚未加载。 调用

(void)genericViewController.view;

快速修复方法是在访问 genericImageView 之前 。这将强制加载视图。 “更好”的方法是给 genericViewController 分配一个图像属性,然后在它的 setter 中你可以说

- (void)setGenericImage:(UIImage *)image {
    if (_genericImage != image) {
        [_genericImage release];
        _genericImage = [image retain];
        if ([self isViewLoaded]) {
            self.genericImageView.image = image;
        }
    }
}

,在 -viewDidLoad 中你可以说

- (void)viewDidLoad {
    [super viewDidLoad];
    self.genericImageView.image = self.genericImage;
}

这个方法,此外更加模块化和架构合理,还有一个优点是,如果视图控制器的视图被卸载(例如,另一个视图被推送到导航堆栈上,并且出现内存警告),当它重新加载时,它仍然会具有图像。

I imagine genericImageView is set up either in a nib or in the -loadView method. However, at the point in which you're trying to access the image view, the view for the VC hasn't been loaded yet. The quick fix is to call

(void)genericViewController.view;

before accessing genericImageView. This will force the view to load. The "better" approach would be to give genericViewController an image property that you assign to, then in its setter you can say

- (void)setGenericImage:(UIImage *)image {
    if (_genericImage != image) {
        [_genericImage release];
        _genericImage = [image retain];
        if ([self isViewLoaded]) {
            self.genericImageView.image = image;
        }
    }
}

and in -viewDidLoad you can say

- (void)viewDidLoad {
    [super viewDidLoad];
    self.genericImageView.image = self.genericImage;
}

This method, besides being more modular and architecturally-sound, also has the advantage where if the view controller's view is unloaded (say, another view is pushed onto the nav stack and a memory warning comes along), when it gets re-loaded it will still have the image.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文