Reputation: 2956
I'm trying to implement a standard UISlider with a custom image.
Currently it looks like so
But I need it to look like this
How do I offset the thumbnail up so only the tip barely touches the line?
Upvotes: 2
Views: 1612
Reputation: 178
If you want to change the offset of the thumb image you have to override thumbRectForBounds:trackRect:value:
in a custom UISlider
subclass.
class CustomSlider: UISlider {
override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
let originalRect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let yOffset: CGFloat = 16 // any value you want
let newY = originalRect.origin.y - yOffset
return CGRect(x: originalRect.origin.x, y: newY, width: originalRect.width, height: originalRect.height)
}
}
Upvotes: 6
Reputation: 18368
When the value of slideBar changed, you can get the thumb position by following codes.
let slideBounds = self.slideBar.bounds
let trackRt = self.slideBar.trackRect(forBounds: slideBounds)
// thumbRt is in slideBar coordination.
let thumbRt = self.slideBar.thumbRect(forBounds: slideBounds, trackRect: trackRt, value: slideBar.value)
// Get center point of slideBar with coordination of `self`.
let centerPt = self.convert(CGPoint(x: thumbRt.midX, y: thumbRt.midY), from: self.slideBar)
// Let a UILabel moving with thumb image of slideBar.
var origPt = self.lblValue.center
origPt.x = centerPt.x
self.lblValue.center = origPt
Upvotes: 0