I created a UIButton instance named \"button\" with an image using [UIButton setImage:forState:]
. The button.frame is larger than the image\'s size.
Now
You must define specific property in Runtime Attributes of Identity inspector – imageView.contentModel
, where you set value relatively to rawValue
position of enum UIViewContentMode
. 1 means scaleAspectFit.
And button's alignment, in Attributes inspector:
Every UIButton has one hidden UIImageView of its own. So we have to set the content mode like the way given below...
[[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];
[btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
An Addition Way for config in XIB file. You can choose this option if you want text or image is Scale full fill in UIButton. It's will be the same with code.
UIButton *btn = [UIButton new];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
Strange, the only combo that worked for me (iOS 5.1) is...
button.imageView.contentMode = UIViewContentModeScaleAspectFit;
and
[button setImage:newImage forState:UIControlStateNormal];
Just do (From Design OR From Code):
[For Point#3: Change Horizontal and vertical Align to UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill]
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
From small test I just did after reading here, depends if you use setImage or setBackgroundImage, both did the same result and strech the image
//for setBackgroundImage
self.imageButton.contentMode = UIViewContentModeScaleAspectFill;
[self.imageButton setBackgroundImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];
//for setImage
self.imageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
self.imageButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
[self.imageButton setImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];