Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 784
Maulik Avatar asked Feb 27 '26 04:02

Maulik


1 Answers

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];
like image 103
Kyle Avatar answered Mar 01 '26 22:03

Kyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!