2

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..

4 Answers 4

9

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];
1
  • For those copy and pasting from this solution, he spelled UIControlStateHighlighted wrong. Oct 25, 2015 at 22:10
3
[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

2

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];
1

Use the sizeToFit method of UIButton (UIView actually).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.