Adding a UIImage View as a subView to an instance of UIView
Asked Answered
S

2

18

I'm practicing beginner code since I'm new and I just have run into a whole lot of confusion here... this is what I have so far

UIView *catView = [[UIView alloc] init];
UIImage *image = [UIImage imageNamed:@"lolcat.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[catView.view addSubview:imageView];

I don't understand what and why something in here is wrong, can someone help?

Staggers answered 9/7, 2013 at 20:19 Comment(4)
What do you see happen? I guess your catView has a zero frame so won't display too wellPinprick
its part of a learning site's code challenge called Treehouse so the editor is online and doesn't show a simulation :(Staggers
So the site just tells you something is wrong and asks you what? You can copy the code into an project and try running it...Pinprick
The line [catView.view addSubview:imageView]; needs to be [catView addSubview:imageView];. And you need to set the frame of catView.Dunt
E
29
//You need to specify the frame of the view   
UIView *catView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,400)];

UIImage *image = [UIImage imageNamed:@"lolcat.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

//specify the frame of the imageView in the superview , here it will fill the superview
imageView.frame = catView.bounds;

// add the imageview to the superview
[catView addSubview:imageView];

//add the view to the main view

[self.view addSubview:catView];
Entirety answered 9/7, 2013 at 20:26 Comment(2)
catView doesn't have a view property.Dunt
oh yeah, i saw that but forgot to remove it when i commented the codeEntirety
E
0

Interesting, and subtle note. If the views have already been added in an .xib file, the views are "weak" and you need to swap with a temp variable. Also some simple math to get the coordinates to match those that you set in your view:

@property (weak, nonatomic) IBOutlet UIImageView *imageView1;
@property (weak, nonatomic) IBOutlet UIImageView *imageView2;
CGRect tempFrame; 

tempFrame = self.imageView1.frame;

CGRect tempFrame;   // use bounds instead

tempFrame = self.imageView2.frame;

__strong UIImageView * tempView = self.imageView2;
[self.imageView2 willMoveToSuperview: nil];
[self.imageView2 removeFromSuperview];
[self.imageView2 willMoveToSuperview: self.imageView1];
[self.imageViewSkate addSubview: self.imageViewBall];
self.imageView2.frame = CGRectMake(tempFrame.origin.x - self.imageView1.frame.origin.x,
                                      tempFrame.origin.y - self.imageView1.frame.origin.y,
                                      tempFrame.size.width, tempFrame.size.height);
tempView = nil;
Existential answered 15/9, 2014 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.