Swift 4 Xcode 9 UISlider 3种颜色从一开始就可见

Swift 4 Xcode 9 UISlider 3 colors visible from the start

如何在 swift 4 Xcode 9 中制作黄色、绿色、红色三种颜色的滑块?它们应该按此顺序排列,如果您启动该应用程序,您将看到它是一个 3 色滑块。没有 tintcolored 滑块在拇指所在的位置改变颜色。如果没有与之交互,它应该是三种颜色的天堂。滑块拇指应在滑块颜色后改变颜色。

我使用 CAGradientLayer 来设计滑块的最大和最小轨道图像,并使用一个矩形作为滑块拇指图像。随意根据您的需要自定义它

 func setSlider(slider:UISlider) {
    let tgl = CAGradientLayer()
    let frame = CGRect(x: 0.0, y: 0.0, width: slider.bounds.width, height: 20.0 )
    tgl.frame = frame

    tgl.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.green.cgColor]

    tgl.borderWidth = 1.0
    tgl.borderColor = UIColor.gray.cgColor
    tgl.cornerRadius = 5.0

    tgl.endPoint = CGPoint(x: 1.0, y:  1.0)
    tgl.startPoint = CGPoint(x: 0.0, y:  1.0)

    UIGraphicsBeginImageContextWithOptions(tgl.frame.size, false, 0.0)
    tgl.render(in: UIGraphicsGetCurrentContext()!)
    let backgroundImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    slider.setMaximumTrackImage(backgroundImage?.resizableImage(withCapInsets:.zero),  for: .normal)
    slider.setMinimumTrackImage(backgroundImage?.resizableImage(withCapInsets:.zero),  for: .normal)

    let layerFrame = CGRect(x: 0, y: 0, width: 10.0, height: 30.0)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = CGPath(rect: layerFrame, transform: nil)
    shapeLayer.fillColor = UIColor.black.cgColor

    let thumb = CALayer.init()
    thumb.frame = layerFrame
    thumb.addSublayer(shapeLayer)

    UIGraphicsBeginImageContextWithOptions(thumb.frame.size, false, 0.0)

    thumb.render(in: UIGraphicsGetCurrentContext()!)
    let thumbImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    slider.setThumbImage(thumbImage, for: .normal)
    slider.setThumbImage(thumbImage, for: .highlighted)
}