user894725
user894725

Reputation: 11

Adding subview doesn't work

- (IBAction)add {

    UIImageView *must = [UIImageView alloc];
    [must setImage:[UIImage imageNamed:@"themustache.png"]];  
    must.center = CGPointMake(0, 0);

    [self.view addSubview:must];
    [must bringSubviewToFront:self.view];
}

When I press a button it should add a mustache, but it doesn't

Upvotes: 0

Views: 192

Answers (6)

- (IBAction)add {

    UIImageView *must = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];

    [must setImage:[UIImage imageNamed:@"themustache.png"] forState:UIControlStateNormal];

    [self.view addSubview:must];

    [must release];
}

Upvotes: 1

viral
viral

Reputation: 4208

Try this and let me know, whether its working or not,

- (IBAction)add {
UIImage *mustImage = [UIImage imageNamed:@"themustache.png"];
UIImageView *must = [[UIImageView alloc] initWithImage:mustImage];
[self.view addSubview:must];  
[mustImage release];
[must release];
}  

or this,

- (IBAction)add {
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);
UIImageView *must = [[UIImageView alloc] initWithFrame:myImageRect];
[must setImage:[UIImage imageNamed:@"themustache.png"]];
[self.view addSubview:must];  
[must release];
}

Try, window instead of self.view if you are calling the function right from AppDelegate.m.
Both of the above, must work for you.

Upvotes: 0

Ravi Chokshi
Ravi Chokshi

Reputation: 1166

Make Sure image named themustache.png exists .. This one worked for me ..

-(IBAction)add {  
UIImageView *must=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0,50, 50)];  
must.image=[UIImage imageNamed:@"themustache.png"];  
[self.view addSubview:must];  
}

Upvotes: 0

Nikunj Jadav
Nikunj Jadav

Reputation: 3402

Try this code, it will help you.
First of all, set the frame of UIImageView and add that imageview into view, it will work fine.

-(IBAction)add  
{
    UIImageView *must = [UIImageView alloc];
    must.frame = CGRectMake(10.0, 50.0, 262.0, 34.0);
    must.backgroundColor = [UIColor clearColor];
    [must setImage:[UIImage imageNamed:@"themustache.png"]];
    [self.view bringSubviewToFront:must];

}

Upvotes: 0

ms83
ms83

Reputation: 1814

Make sure the button is connected to the right action in Interface Builder. Also put this in your add method NSLog(@"Pressed");. If it is connected you should see the Pressed message displayed in the console every time you press the button.

Upvotes: 0

user885074
user885074

Reputation: 491

Why are you telling must to bring its parent to the front? Try this: [self.view bringSubviewToFront:must];

Upvotes: 0

Related Questions