How to change the corner radius of UISegmentedControl?
This should work:
self.segmentedControl.layer.cornerRadius = 15.0;self.segmentedControl.layer.borderColor = [UIColor whiteColor].CGColor;self.segmentedControl.layer.borderWidth = 1.0f;self.segmentedControl.layer.masksToBounds = YES;
You need to specify the border after setting cornerRadius.
Embed UISegmentedControl inside UIView and set corner radius for UIView.
Objective-C
outerView.layer.cornerRadius = CGRectGetHeight(outerView.bounds) / 2;outerView.layer.borderColor = [UIColor blueColor].CGColor;outerView.layer.borderWidth = 1;
Swift
outerView.layer.cornerRadius = CGRectGetHeight(outerView.bounds) / 2outerView.layer.borderColor = UIColor.blueColor().CGColorouterView.layer.borderWidth = 1
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)