UISlider 并不能满足平时开发的需求,比如渐变色,可以正负左右滑动带渐变的美颜滑块等等 。鄙人参考网上各种大神的写法,自定义写了 UISlider自定义,自诩效果交互都是很好的。如有更好的想法,欢迎留言沟通
先上效果
效果如图
具体demo下载地址: https://gitee.com/enterprise-and-taiwan/xaxis-slider
思路如下:
重写 UISlider 的 override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect
1.渐变色整体滑动的slider
把原来的slider背景色置为: maximumTrackTintColor = .clear minimumTrackTintColor = .clear
自定义 背景色的view 与滑动的view 重写 方法 override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect { let result = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let result = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let orign = result.origin
let size = result.size
let centerX = orign.x + size.width/2.0
let centerY = orign.y + size.height/2.0
arrowImgView.frame = CGRect(origin: CGPoint(x: centerX - 3, y: orign.y - 8), size: CGSize(width: 6, height: 6))
// 2是 微调距离; 0.5 是微调 y
lineSelectView.frame = CGRect(x: 2, y: centerY - sliderHeight/2.0-0.5, width: centerX, height: sliderHeight)
titleLabel.text = "\(Int(value))"
return result
} ```
2.有正负左右滑动的 slider,同上,多加一个滑块view.同样重写
override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
let result = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let orign = result.origin
let size = result.size
let centerX = orign.x + size.width/2.0
let centerY = orign.y + size.height/2.0
let totalSize = rect.size
// 永远在 thumb的中心位置
arrowImgView.frame = CGRect(origin: CGPoint(x: centerX - 3, y: orign.y - 8), size: CGSize(width: 6, height: 6))
// 2是 微调距离; 0.5 是微调 y
if value > 0 {
// 左边置灰,右边有颜色
leftLineSelectView.startColor = .gray
leftLineSelectView.endColor = .gray
leftLineSelectView.frame = CGRect(x: 2, y: centerY - sliderHeight/2.0-0.5, width: totalSize.width/2.0+2, height: sliderHeight)
rightLineSelectView.startColor = .orange
rightLineSelectView.endColor = .yellow
rightLineSelectView.frame = CGRect(x: totalSize.width/2.0+2, y: centerY - sliderHeight/2.0-0.5, width: totalSize.width*CGFloat((value/(maximumValue-minimumValue))), height: sliderHeight)
}else{
//右边置灰 ,左边有颜色
leftLineSelectView.startColor = .orange
leftLineSelectView.endColor = .yellow
let leftWidth = totalSize.width*CGFloat((value*(-1)/(maximumValue-minimumValue)))
leftLineSelectView.frame = CGRect(x: totalSize.width/2.0-leftWidth+2, y: centerY - sliderHeight/2.0-0.5, width:leftWidth+2 , height: sliderHeight)
rightLineSelectView.startColor = .gray
rightLineSelectView.endColor = .gray
rightLineSelectView.frame = CGRect(x: totalSize.width/2.0+2, y: centerY - sliderHeight/2.0-0.5, width: totalSize.width/2.0-4, height: sliderHeight)
}
titleLabel.text = "\(Int(value))"
return result
}
具体demo下载地址: https://gitee.com/enterprise-and-taiwan/xaxis-slider
如有更好的想法,欢迎留言沟通