Is that possible to add a label to the UISlider

2019-02-09 06:42发布

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.

8条回答
相关推荐>>
2楼-- · 2019-02-09 07:16

Well, I subclassed the UISlider and override the methods of NSControl. You just need to change your class into storyboard

I label can be add above thumb as per requirement.

class CustomSlider: UISlider {


let label = UILabel()

override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    let track = super.beginTracking(touch, with: event)
    label.text = "\(Int(self.value))"
    label.frame = CGRect.init(x: self.thumbCenterX, y: -10, width: 20, height: 20)
    self.addSubview(label)
    return track
}


override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    let track = super.continueTracking(touch, with: event)
    label.frame = CGRect.init(x: self.thumbCenterX - 5 , y: 6, width: 30, height: 20)
    label.text = "\(Int(self.value))"
    return track
}

override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
    super.endTracking(touch, with: event)
    label.removeFromSuperview()
}}



extension UISlider {
var thumbCenterX: CGFloat {
    let trackRect = self.trackRect(forBounds: frame)
    let thumbRect = self.thumbRect(forBounds: bounds, trackRect: bounds, value: value)
    return thumbRect.midX
}}
查看更多
孤傲高冷的网名
3楼-- · 2019-02-09 07:20

Add a UISlider and a UILabel in Interface Builder. Create IBOutlets to access them in code and add a IBAction to respond to changes of the slider value.

Then in your code write:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.slider addSubview:self.label];
    [self valueChanged:self.slider];
}

- (IBAction)valueChanged:(id)sender {
    self.label.center = CGPointMake(self.slider.value*self.slider.bounds.size.width, 40);
    self.label.text = [NSString stringWithFormat:@"%0.2f", self.slider.value];
}

EDIT: To create the slider and label with code add this:

-(void)loadView {
    [super loadView];
    self.slider = [[[UISlider alloc] initWithFrame:CGRectMake(50, 150, 200, 30)] autorelease];
    self.label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 30)] autorelease];
    [self.label setBackgroundColor:[UIColor clearColor]];
    [self.slider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];

}
查看更多
登录 后发表回答