Jarrod
Jarrod

Reputation: 1705

How do I programmatically add a UIImage to a UIImageView then add that UIImageView to another UIView?

As the title says, I'm trying to create a UIImage that will go inside a UIImageView (so that I can animate it later) then I want to put that UIImageView into another classes UIView.

So far my relevant code is:

This is the viewDidLoad for my root view controller:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.playerViewController = [[TUKIPlayerViewController alloc] init];
    [self.view addSubview:playerViewController.view];
}

And this is the init for the UIImageView:

- (id)init
{
    if (self = [super init]) {
        playerIdle = [UIImage imageNamed:@"playerIdle.png"];
        playerView = [[UIImageView alloc] initWithImage:playerIdle];
        self.view = playerView;
    }
    return self;
}

It builds and runs with 0 errors.

What am I doing wrong? I don't see the playerIdle.png anywhere. Though I'm betting I'm doing this terribly wrong.

Upvotes: 7

Views: 16070

Answers (6)

saravanan R
saravanan R

Reputation: 1

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"name.png"]]; imagView.frame=CGRectMake(40,130,45,45);

[self.view addSubview:imgView];

Upvotes: 0

Alex Spencer
Alex Spencer

Reputation: 862

Or you could try: myUIImageViewObject.image = myUIImageObject;

Upvotes: 0

Novarg
Novarg

Reputation: 7440

You should use [self.view addSubview:playerView]; instead of just setting it(self.view = playerview;). What I also do most of the times is bringing that subview to the front:

[self.view bringSubviewToFront:playerView];

Hope it helps

Upvotes: 1

Atulkumar V. Jain
Atulkumar V. Jain

Reputation: 5098

Pls try the below code :

- (id)init 
{
     if (self = [super init]) {
         playerIdle = [UIImage imageNamed:@"playerIdle.png"];
         playerView = [[UIImageView alloc] initWithImage:playerIdle];
         [self.view addSubview:playerView];
     }
return self; 
} 

Hope this might help you.....

Upvotes: 4

Deviator
Deviator

Reputation: 688

Try this:

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"name.png"]];
[self.view addSubview:imgView];

Upvotes: 4

Akash Malhotra
Akash Malhotra

Reputation: 1106

In your ViewController , add the imageview directly...

- (void)viewDidLoad
{
   playerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"playerIdle.png"]];
   [self.view addSubView: playerView];
}

Upvotes: 13

Related Questions