iOS 13 / 14 - FINALLY WORKING!!!
I decided to give it another go, and I finally got it working perfectly!!
There's one line of code that fixed it all! Check out the code
Code:
class CustomSegmentedControl: UISegmentedControl{
private let segmentInset: CGFloat = 5 //your inset amount
private let segmentImage: UIImage? = UIImage(color: UIColor.red) //your color
override func layoutSubviews(){
super.layoutSubviews()
//background
layer.cornerRadius = bounds.height/2
//foreground
let foregroundIndex = numberOfSegments
if subviews.indices.contains(foregroundIndex), let foregroundImageView = subviews[foregroundIndex] as? UIImageView
{
foregroundImageView.bounds = foregroundImageView.bounds.insetBy(dx: segmentInset, dy: segmentInset)
foregroundImageView.image = segmentImage //substitute with our own colored image
foregroundImageView.layer.removeAnimation(forKey: "SelectionBounds") //this removes the weird scaling animation!
foregroundImageView.layer.masksToBounds = true
foregroundImageView.layer.cornerRadius = foregroundImageView.bounds.height/2
}
}
}
extension UIImage{
//creates a UIImage given a UIColor
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
The idea is that Apple uses a UIImageView with its own square image and tint for the selected moving segment. What we want to do is instead overwrite its image so we have control on the color, corner radius, etc. After that, we want to remove one of Apple's 3 default animations (the one that was problematic made the segment scale up on touch -- I used foregroundImageView.layer.animationKeys()
to find out what animations were affecting the moving segment)