UISlider滑动条的高度系统默认给我们设定了,没有办法进行改变。可是,我们的设计又是需要改变这个高度的,怎么办呢?这个时候,我们可以写一个UISlider的子类,重写四个方法就能实现了。
//
// CustomSlider.swift
// CustomSlider
//
// Created by iOS on 2018/4/4.
// Copyright © 2018年 weiman. All rights reserved.
//
import UIKit
class CustomSlider: UISlider {
var height: CGFloat = 0.0
override func minimumValueImageRect(forBounds bounds: CGRect) -> CGRect {
return self.bounds
}
override func maximumValueImageRect(forBounds bounds: CGRect) -> CGRect {
return self.bounds
}
// 控制slider的宽和高,这个方法才是真正的改变slider滑道的高的
override func trackRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.trackRect(forBounds: bounds)
return CGRect.init(x: rect.origin.x, y: (bounds.size.height-height)/2, width: bounds.size.width, height: height)
}
// 改变滑块的触摸范围
override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
return super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
}
}
使用:
lazy var slider: CustomSlider = {
$0.setThumbImage(#imageLiteral(resourceName: "sliderThumbImage"), for: .normal)
$0.height = 5 //设置高度
$0.maximumTrackTintColor = .clear
$0.minimumTrackTintColor = UIColor(red: 174/255.0, green: 119/255.0, blue: 255/255.0, alpha: 1.0)
$0.addTarget(self,
action: #selector(sliderTouchDown(slider:)),
for: .touchDown)
$0.addTarget(self,
action: #selector(sliderEnd(slider:)),
for: .touchUpInside)
return $0
}( CustomSlider() )
效果: