Maulik
Maulik

Reputation: 19418

uibutton with image

I am having a button using IB. Now i want to add an image to the button programmatically. how can I set the button's size of image's size like we do in IB Layout -> Size to Fit . I want to do it programmatically

Thanks..

Upvotes: 2

Views: 10533

Answers (4)

Kyle
Kyle

Reputation: 1595

You can add an image to the button using UIButton's setImage:forState: method and then you set the content sizing using UIView's contentMode property.

An example would look like this:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:@"myImage.png"];

button.frame = CGRectMake(20, 100, img.size.width, img.size.height);

[button setImage:img forState:UIControlStateNormal];
[button setImage:img forState:UIControlStateHighlighted];
[button setImage:img forState:UIControlStateSelected];

button.contentMode = UIViewContentModeScaleToFill; //Look up UIViewContentMode in the documentation for other options

[self.view addSubview:button];

Upvotes: 9

pbernery
pbernery

Reputation: 646

Use the sizeToFit method of UIButton (UIView actually).

Upvotes: 1

visakh7
visakh7

Reputation: 26390

[yourButton setImage:yourImage forState:UIControlStateNormal];
yourButton.contentMode = UIViewContentModeScaleToFill;

where the the values for contentMode can be any one of the below

typedef enum {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
} UIViewContentMode;

I think this could help you

Upvotes: 3

Chetan Bhalara
Chetan Bhalara

Reputation: 10344

Sample Code,

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img1 = [UIImage imageNamed:@"image1.png"];
btn.frame = CGRectMake(20.0 , 270.0, img1.size.width, img1.size.height);
[btn setImage:img1 forState:UIControlStateNormal]; 
UIImage *img2 = [UIImage imageNamed:@"image2.png"];
[btn setImage:img2 forState:UIControlStateHighlighted];
[btn setImage:img2 forState:UIControlStateSelected];
[btn addTarget:self action:@selector(Action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

Upvotes: 2

Related Questions