Is there a way to set a UIButton Image, BackgroundImage or ImageView Properties Content Mode Property?
I've tried the direct approach (it didn't work, of course...):
self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
It's nice to have a button with an image, but if there's no way to set it properly, it's not very handy...
Using iOS7/8 with auto-layout,
button.imageView
doesn't get scaled whenbutton
is laid out, e.g. for iPhone 6:After setting
button
's image,button.imageView
assumed the size of the image, e.g. for a 320x240 image:It looks like
button.imageView
does not respect its content mode, but actually, it is the size of thebutton.imageView
that is the problem.The answer is to set
button
's content alignment as well.The following sets
button
's image, setsbutton.imageView
's content mode, and makesbutton.imageView
fit the size ofbutton
:Now,
button.imageView
is the same size asbutton
, and has the desired content mode.The desired result is thereby achieved. Very handy!
if you don't want to subclass UIButton than you can try this,
Every UIButton has one hidden UIImageView of its own. So we have to set the content mode like the way given below...