文章目录
- 1.改变进度条的高度(亲测有效)
- 2.改变圆形滑块的大小(亲测有效)
1.改变进度条的高度(亲测有效)
import UIKitclass CustomSlider: UISlider {// 设置轨道高度var trackHeight: CGFloat = 10// 重写 trackRect(forBounds:) 方法来自定义轨道的尺寸override func trackRect(forBounds bounds: CGRect) -> CGRect {// 获取默认的轨道矩形var rect = super.trackRect(forBounds: bounds)// 修改矩形的高度rect.size.height = trackHeightreturn rect}
}// 使用示例
let slider = CustomSlider(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
slider.trackHeight = 20 // 设置进度条的宽度为20点
2.改变圆形滑块的大小(亲测有效)
import UIKitclass ViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()// 创建 UISliderlet slider = UISlider(frame: CGRect(x: 50, y: 100, width: 300, height: 50))self.view.addSubview(slider)// 创建一个50x50点的自定义滑块图像let thumbImage = UIImage(named: "customThumbImage") // 确保您有一个名为 "customThumbImage" 的50x50点的图像slider.setThumbImage(thumbImage, for: .normal)}
}
- 用下面的方法圆形滑块的大小没有变化
import UIKitclass CustomSlider: UISlider {// 设置滑块的大小var thumbSize: CGSize = CGSize(width: 30, height: 30)// 重写 thumbRect 方法来自定义滑块的尺寸override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {// 获取默认的滑块矩形let defaultRect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)// 计算新的滑块矩形let newRect = CGRect(x: defaultRect.origin.x, y: defaultRect.origin.y + (defaultRect.size.height - thumbSize.height) / 2, width: thumbSize.width, height: thumbSize.height)return newRect}
}// 使用示例
let slider = CustomSlider(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
slider.thumbSize = CGSize(width: 40, height: 40) // 设置滑块的大小为40x40