I have a UIButton with no text and have 2 images I'd like to use (one for normal state and the other for selected state). The images are smaller than the button size.
How do I ensure that neither of the images are scaled when the button is drawn? Setting the imageView properties only change the scale correctly for normal state but not for selected.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:imageNormal forState:UIControlStateNormal];
[button setImage:imageSelected forState:UIControlStateSelected];
// this shows the correct scale in normal mode but not when button is tapped
button.imageView.contentScaleFactor = 1.0;
button.imageView.contentMode = UIViewContentModeCenter;
Assuming you have the image height and width you could do this:
int topBottom = (button.frame.size.height - imageHeight) / 2;
int leftRight = (button.frame.size.width - imageWidth) / 2;
button.imageEdgeInsets = UIEdgeInsetsMake(topBottom,leftRight,topBottom,leftRight);
And then you don't need to set the contentMode/scalefactor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With