UISegmentedControl maintain aspect ratio on image

Multi tool use
UISegmentedControl maintain aspect ratio on image
I'm having a hard time making images on a UISegmentedControl keep their aspect ratio and not scale to all sides.
Here's what it looks like:
The images are 100X100(except nr 6 gonna replace soon) and I want them to maintain the aspect ratio.
I have tried:
self.segment.contentMode = .ScaleAspectFit
//and:
self.segment.contentMode = UIViewContentMode.Center
Are there a way I can target the UIImageView in the segment..that way I can set the contentMode..right? Or is there another approach?
Thanks
3 Answers
3
segmentedControl.subviews.flatMap{$0.subviews}.forEach { subview in
if let imageView = subview as? UIImageView, let image = imageView.image, image.size.width > 5 {
// The imageView which isn't separator
imageView.contentMode = .scaleAspectFit
}
}
This is the only solution of found that actually works reliably. However, I'm having a hard time figuring out when (i.e., where in code) to execute it. I have a UISegmentedControl subclass, and tried putting it in awakeFromNib, but it didn't work. I also have a target action on .valueChanged, and when I handle it there it works. So there's something about the order of (re)drawing that clearly makes a difference. In my case, it's in a table view cell, so perhaps a layoutSubviews is running?
– mrwheet
Jul 1 at 17:14
I didn't find how to set the contentMode to ScaleAspectFit but you can use the following code to set a margin around your image when you are setting the image :
yourSegmentedControl.setImage(yourImage.resizableImage(withCapInsets: .init(top: 0, left: 10, bottom: 0, right: 10), resizingMode: .stretch), forSegmentAt: 0)
You can change the values of "top", "left", "bottom" and "right" as you want.
This worked for me, I hope it will help!
Actually, there's a great, general purpose solution for this:
UIImageView.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).contentMode = .scaleAspectFit
This uses the approach described here: UIImageView.appearance is overriding UISegmentedControl.appearance
In my case, I constrained it to a subclass of UISegmentedControl (in case I want the default aspectFill for other situations).
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please add an explanation.
– Xcoder
May 5 at 18:33