UISlider:更改了高度,但最大值闪烁

UISlider: changed hight, but maximum value flashes

我自定义了一个 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% 图片:

这里有一些快速解决方案

您更改了线条的框架,高度高于默认值,这就是您看到它的原因。

您可以将滑块移动到 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
}

或者你可以把拇指变大以覆盖角落,这取决于你。

原始答案在这里: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)
}

您可以通过将minimumTrackTintColormaximumTrackTintColor设置为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()
    }

}