How to make UISlider default thumb to be smaller like the ones in the iOS control center

后端 未结 5 550
孤独总比滥情好
孤独总比滥情好 2021-02-01 06:50

I\'m working on an app and I have a custom UISlider.
However, I\'m having some issues on how to make the default thumb to appear smaller like t

5条回答
  •  滥情空心
    2021-02-01 07:41

    If you want to change Thumb Image as well as Tint Color then both can't be possible; There is one workaround of this issue. Create circular image programmatically and change the color of the image and assign that image to slider thumb; In this way, you can also resize the image as well as color.

    Here is the fully working sample code:

    fileprivate func makeCircleWith(size: CGSize, backgroundColor: UIColor) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(backgroundColor.cgColor)
        context?.setStrokeColor(UIColor.clear.cgColor)
        let bounds = CGRect(origin: .zero, size: size)
        context?.addEllipse(in: bounds)
        context?.drawPath(using: .fill)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    

    You can call this function like this:

        func setSliderThumbTintColor(_ color: UIColor) {
        let circleImage = makeCircleWith(size: CGSize(width: 20, height: 20),
                       backgroundColor: color)
        slider.setThumbImage(circleImage, for: .normal)
        slider.setThumbImage(circleImage, for: .highlighted)
    }
    

    This method setSliderThumbTintColor will be called on valueChanged event of UISlider.

提交回复
热议问题