Question

In my UIView subclass' .h:

@interface MyView : UIView
@property (nonatomic, strong) UIImageView *imageView;
@end

I'm setting up the UIImageView on my UIView subclass like this (init method):

self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 34, 34)];
self.imageView.layer.cornerRadius = CGRectGetWidth(imageView.frame) / 2.0f;
self.imageView.layer.masksToBounds = YES;
self.imageView.backgroundColor = [UIColor someColor];
[self addSubview: self.imageView];

So, I can do myView.imageView.image = [UIImage someImage] and it sets the image on the UIImageView correctly. My problem comes when trying to clean up the code on my UIView subclass.

I'm trying to do this:

- (UIImageView *)imageView {
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 34, 34)];
    imageView.layer.cornerRadius = CGRectGetWidth(profilePhotoImageView.frame) / 2.0f;
    imageView.layer.masksToBounds = YES;
    imageView.backgroundColor = [UIColor redColor];

    return imageView;
}

and then from the init method do

[self addSubView: [self imageView]];

But when I do myView.imageView.image = [UIImage someImage] the image doesn't show on the UIImageView.

What am I forgetting?

Was it helpful?

Solution

Make sure that your imageView getter method is getting the UIImageView instance already stored in the instance variable _imageView. Otherwise each time you call the imageView method, you're creating a new instance of a UIImageView, so you're not going to be setting the image on the instance that actually got added to your view.

So, here's how your imageView method should look:

- (UIImageView *) imageView {
    UIImageView *imageView = _imageView;
    imageView.layer.cornerRadius = CGRectGetWidth(profilePhotoImageView.frame) / 2.0f;
    imageView.layer.masksToBounds = YES;
    imageView.backgroundColor = [UIColor redColor];

    return imageView;
}

OTHER TIPS

When you name your method imageView, it overrides the getter for your property. So every time you call it, you're calling the method and creating a new UIImageView.

IE,

myView.imageView

and

[myView imageView]

both call the method you defined, which returns a new UIImageView, not the one you created in init.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top