I have a couple UIButtons, and in IB they\'re set to Aspect Fit, but for some reason they\'re always stretching. Is there something else you have to set? I tried all the d
I had this problem a while back. The issue I had was i was trying to apply this effect to the background UIButton which is limited and therefore means you cannot adjust it as easy.
The trick is to set it as just an image then apply @ayreguitar's technique and that should fix it!
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setContentMode:UIViewContentModeScaleAspectFill];
[myButton setImage:@"myImage.png" forState:UIControlStateNormal];
Here's an alternative answer in swift:
myButton.imageView?.contentMode = .ScaleAspectFit
The solution is to set the contentMode
on the imageView
property of the UIButton
. The UIButton
has to be created with custom type for this to work I believe (otherwise nil
is returned for this property).
ios 12. You need to add also the content Alignment
class FitButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
self.imageView?.contentMode = .scaleAspectFill
self.contentHorizontalAlignment = .fill
self.contentVerticalAlignment = .fill
super.layoutSubviews()
}
}
I've had that problem before. I solved it by putting my image in a UIImageView
, where contentMode
settings actually work, and putting a transparent custom UIButton
over top of that.
EDIT: This answer is obsolete. See @Werner Altewischer's answer for the correct answer in modern versions of iOS.
Similar to @Guillaume, I have created a subclass of UIButton as a Swift-File. Then set my custom class in the Interface Builder:
.
And here the Swift file:
import UIKit
class TRAspectButton : UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.imageView?.contentMode = .ScaleAspectFit
}
}