izan
izan

Reputation: 737

ImageView and UIButton

I would like to create a button with a custom image ( background image), i have done this. how can assign the imageview to may button ?

thanks for your answers

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
           action:@selector(goToGeoloc)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0);
UIImage *image = [UIImage imageNamed:@"ico_plan.png"];
UIImageView *imageView = [[UIImageView alloc]initWithImage:image];

Upvotes: 4

Views: 13660

Answers (4)

Robin
Robin

Reputation: 10011

@izan you dont need a separate UIImageView to show on the UIButton.

A UIButton comes with 2 UIImageView inside it. you can just set the image for these 2 imageViews.

You can set the image for the first imageview using setImage:forState: method. By doing this you cannot show any title for that button. If you want to show title as well as image on the button you should use setBackgroundImage:forState: method.

Upvotes: 6

visakh7
visakh7

Reputation: 26400

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
           action:@selector(goToGeoloc)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"ico_plan.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0);

Hope this helps

Upvotes: 0

Thizzer
Thizzer

Reputation: 16663

Use the setImage method;

- (void)setImage:(UIImage *)image forState:(UIControlState)state

So your code would be;

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(goToGeoloc) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0);

UIImage *image = [UIImage imageNamed:@"ico_plan.png"];
[button setImage:image forState:UIControlStateNormal];

Or I you still want your text to be shown use;

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state

Which would result in;

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(goToGeoloc) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0);

UIImage *image = [UIImage imageNamed:@"ico_plan.png"];
[button setBackgroundImage:image forState:UIControlStateNormal];

UIButton documentation; http://bit.ly/kruq5y

Upvotes: 5

tamasgal
tamasgal

Reputation: 26329

What you want is:

[button setBackgroundImage:image forState:UIControlStateNormal];

or

[button setImage:image forState:UIControlStateNormal];

Upvotes: 7

Related Questions