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

后端 未结 5 613
孤独总比滥情好
孤独总比滥情好 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:38

    I created a UISlider subclass that allows to change the thumb size as well as track size, all without using images.

    import UIKit
    
    class CustomSlider: UISlider {
    
        @IBInspectable var trackHeight: CGFloat = 3
    
        @IBInspectable var thumbRadius: CGFloat = 20
    
        // Custom thumb view which will be converted to UIImage
        // and set as thumb. You can customize it's colors, border, etc.
        private lazy var thumbView: UIView = {
            let thumb = UIView()
            thumb.backgroundColor = .yellow//thumbTintColor
            thumb.layer.borderWidth = 0.4
            thumb.layer.borderColor = UIColor.darkGray.cgColor
            return thumb
        }()
    
        override func awakeFromNib() {
            super.awakeFromNib()
            let thumb = thumbImage(radius: thumbRadius)
            setThumbImage(thumb, for: .normal)
        }
    
        private func thumbImage(radius: CGFloat) -> UIImage {
            // Set proper frame
            // y: radius / 2 will correctly offset the thumb
    
            thumbView.frame = CGRect(x: 0, y: radius / 2, width: radius, height: radius)
            thumbView.layer.cornerRadius = radius / 2
    
            // Convert thumbView to UIImage
            // See this: https://stackoverflow.com/a/41288197/7235585
    
            let renderer = UIGraphicsImageRenderer(bounds: thumbView.bounds)
            return renderer.image { rendererContext in
                thumbView.layer.render(in: rendererContext.cgContext)
            }
        }
    
        override func trackRect(forBounds bounds: CGRect) -> CGRect {
            // Set custom track height
            // As seen here: https://stackoverflow.com/a/49428606/7235585
            var newRect = super.trackRect(forBounds: bounds)
            newRect.size.height = trackHeight
            return newRect
        }
    
    }
    

    Result:

提交回复
热议问题