Search code examples
iosswiftuisegmentedcontrol

How to remove border from segmented control


How do I remove the outside border of a segmented control? I've set the divider image to what I wanted but now to follow the mock of my app I need to have a segmented control without the outer border.


Solution

  • What you must understand is the backgroundColor property is not stateful. Hence you have to use setBackgroundImage(_:for:barMetrics:).

    We can easily remove both borders and dividers using the below function.

    For Swift 3 & 4+:

    extension UISegmentedControl {
        func removeBorders() {
            setBackgroundImage(imageWithColor(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
            setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
            setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
        }
    
        // create a 1x1 image with this color
        private func imageWithColor(color: UIColor) -> UIImage {
            let rect = CGRect(x: 0.0, y: 0.0, width:  1.0, height: 1.0)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()
            context!.setFillColor(color.cgColor);
            context!.fill(rect);
            let image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return image!
        }
    }
    

    For Swift 2.2:

    extension UISegmentedControl {
        func removeBorders() {
            setBackgroundImage(imageWithColor(backgroundColor!), forState: .Normal, barMetrics: .Default)
            setBackgroundImage(imageWithColor(tintColor!), forState: .Selected, barMetrics: .Default)
            setDividerImage(imageWithColor(UIColor.clearColor()), forLeftSegmentState: .Normal, rightSegmentState: .Normal, barMetrics: .Default)
        }
    
        // create a 1x1 image with this color
        private func imageWithColor(color: UIColor) -> UIImage {
            let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()
            CGContextSetFillColorWithColor(context, color.CGColor);
            CGContextFillRect(context, rect);
            let image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return image
        }
    }
    

    Call the above function.

    segmentedControl.removeBorders()
    

    Reference: Remove UISegmentedControl separators completely. (iphone)

    Thanks to https://stackoverflow.com/users/3921490/amagain for Swift 3 version.