我自定义了UISlider
,除了将滑块拖动到100%之外,其他一切都运行良好。然后,将圆形帽替换为正方形。
这是我自定义滑块的方法:
@IBInspectable var trackHeight: CGFloat = 14
override func trackRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: trackHeight))
}
98%图片:
100%图片:
答案 0 :(得分:0)
这里有一些快速的解决方法
您更改了该行的框架,其高度比默认值高,这就是为什么看到它的原因。
您可以将滑块稍微移动100%。
override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
var rect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
if value > 0.99 {
rect = CGRect(x: rect.origin.x+2, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
}
return rect
}
或者您可以将拇指变大以遮盖角落,这取决于您。
答案 1 :(得分:0)
此处的原始答案:Thumb image does not move to the edge of UISlider
更新为Swift 4.2:
override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
let unadjustedThumbrect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let thumbOffsetToApplyOnEachSide:CGFloat = unadjustedThumbrect.size.width / 2.0
let minOffsetToAdd = -thumbOffsetToApplyOnEachSide
let maxOffsetToAdd = thumbOffsetToApplyOnEachSide
let offsetForValue = minOffsetToAdd + (maxOffsetToAdd - minOffsetToAdd) * CGFloat(value / (self.maximumValue - self.minimumValue))
var origin = unadjustedThumbrect.origin
origin.x += offsetForValue
return CGRect(origin: origin, size: unadjustedThumbrect.size)
}
答案 2 :(得分:0)
您可以通过将minimumTrackTintColor
和maximumTrackTintColor
设置为UIColor.clear
来删除轨道背景,然后自己绘制轨道背景。
例如:
class CustomSlider: UISlider {
override func trackRect(forBounds bounds: CGRect) -> CGRect {
return bounds
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.setFillColor(UIColor.green.cgColor)
let path = UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height / 2).cgPath
context.addPath(path)
context.fillPath()
}
}