向 UISegmentedControl 添加边框

Add Border to UISegmentedControl

如何设置边框颜色为 UISegmentedControl

我默认得到这个(不正确):

我正在尝试这个但没有任何反应

UISegmentedControl.appearance().layer.borderWidth = 1.0
UISegmentedControl.appearance().layer.cornerRadius = 5.0
UISegmentedControl.appearance().layer.borderColor = UIColor.white.cgColor
UISegmentedControl.appearance().layer.masksToBounds = true

我想实现这个边框(正确):

我使用这个函数来改变我的 SegmentedControl:

func setSegmentedControlStyle(_ sgControl: UISegmentedControl, withColor: UIColor, normalTextColor: UIColor, withCornorRadius: CGFloat) {
        let sgcTitleAttributes = [NSAttributedString.Key.font: UIFont.nunitoSansRegularFontOfSize(15.0)!,
                                  NSAttributedString.Key.foregroundColor: normalTextColor] as [NSAttributedString.Key : Any]
        let sgcSelectedStateTitleAttributes = [NSAttributedString.Key.font: UIFont.nunitoSansRegularFontOfSize(15.0)!,
                                               NSAttributedString.Key.foregroundColor: _WHITE_COLOR] as [NSAttributedString.Key : Any]

    if #available(iOS 13.0, *) {
        sgControl.backgroundColor = UIColor.clear
        let tintColorImage = UIImage(color: .clear, size: CGSize(width: 1, height: sgControl.frame.height))
        let selectedTintColorImage = UIImage(color: withColor, size: CGSize(width: 1, height: sgControl.frame.height))
        sgControl.setBackgroundImage(tintColorImage, for: .normal, barMetrics: .default)
        sgControl.setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
        sgControl.setBackgroundImage(selectedTintColorImage, for: .selected, barMetrics: .default)
        sgControl.selectedSegmentTintColor = withColor
    } else {
        sgControl.tintColor = withColor
    }
    sgControl.layer.cornerRadius = withCornorRadius
    sgControl.layer.borderWidth = 1.0
    sgControl.layer.borderColor = withColor.cgColor
    sgControl.layer.masksToBounds = true
    sgControl.setTitleTextAttributes(sgcTitleAttributes, for: .normal)
    sgControl.setTitleTextAttributes(sgcSelectedStateTitleAttributes, for: .selected)
}


extension UIImage {
    convenience init(color: UIColor, size: CGSize) {
        UIGraphicsBeginImageContextWithOptions(size, false, 1)
        color.set()
        let ctx = UIGraphicsGetCurrentContext()!
        ctx.fill(CGRect(origin: .zero, size: size))
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        self.init(data: image.pngData()!)!
    }
}

你可以根据自己的需要随意改变一下。

如果您有任何问题,请告诉我。

乐于助人!