I want to add a label to the slider's thumb which should show the value of the slider and changes too when thumbs is being dragged towards right side. Is it possible??
Any comments or suggestion would be appreciated.
I want to add a label to the slider's thumb which should show the value of the slider and changes too when thumbs is being dragged towards right side. Is it possible??
Any comments or suggestion would be appreciated.
You could do something similar to this example which draws text directly to your thumb image. It's a rough example so you will need to change it to make sense for your project.
I grab the thumb image from the slider (UIImageView) and add my label to it. Nice and clean.
Then you change the label.text whenever you need to.
Note: the subview order of UISlider could change in the future, however it's unlikely that the thumb would no longer be the topmost view, as it will always be the main point of interaction in a slider.
Swift 3 -- More detailed example (link your slider in IB)
You can access the rect for the slider's thumb image view with
-thumbRectForBounds:trackRect:value:]
, so if you add aUILabel
subview you can align it relative to the thumb image view in-layoutSubviews
using this returned rect.However, if you'd like to use Autolayout to align your label with the thumb image then you need access to the thumb's
UIImageView
directly. I'm not keen on spelunking the subviews ofUIKit
kit components generally, but I think you can use details of the public API to search for the image view in a future-proofed way:- (UIImageView*) thumbImageView { __block UIImageView *imageView = nil; [self.subviews enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(UIImageView *candidate, NSUInteger idx, BOOL *stop) { if ([candidate isKindOfClass:[UIImageView class]] && candidate.image == [self thumbImageForState:UIControlStateNormal]) { imageView = candidate; *stop = YES; } }]; return imageView; }
The API provides the ability to set a
UIImage
for the thumb, so you can use this as a test to ensure that you aren't getting some other image view. This is even safer if you are explicitly setting a thumb image yourself (since it's not impossible that the slider might be changed to draw the thumb image in future...). Also, the thumb image view is currently the last subview (not guaranteed going forward), so I'm doing a reverse enumeration here to hopefully get it as faster as possible whilst not making assumptions about its index.NB: I had to create my thumb label lazily, since
UISlider
's subviews seem to be so.A simple implementation of a custom class in Swift 3.2. This is working nicely for me.
I hope it helps :)
make this nice and easy.. first off this is the final result
and now, code:
the above methods are used from an
NSLayoutConstraint
category i use (coming soon)