views:

530

answers:

1

Is it possible to set an UISlider as first responder and set its current value to the location of the current touch programatically?

The way my app is set up I have a UIView container that takes up the whole screen. Inside the container I have another UIView offscreen at the bottom edge (I'll call this bottomBar). Inside the bottomBar there is a UISlider element.

The idea is that when the user swipes along the bottom edge of the screen, the bottomBar with the slider move into the view. What I am trying to achieve is to activate the UISlider, and set the position of the slider (the value) to the position of the users touch. Is this possible?

I did figure out a pretty ugly hack to get this done. But there has to be a more elegant solution than this?

CGPoint sliderPos = [touch locationInView:pageSlider];
float newSliderValue = sliderPos.x/pageSlider.frame.size.width*pageSlider.maximumValue;
if (sliderPos.x<=0) {
    pageSlider.value = 0;
}
else if(newSliderValue>=pageSlider.maximumValue) {
    pageSlider.value = pageSlider.maximumValue;
}
else {
    pageSlider.value = newSliderValue;  
}

Two specific problems I have with the code above is that it a) doesn't position the thumb exactly right because it ignores the length of the thumb, and b) the thumb isn't highlighted as it moves.

A: 

You can use the method - (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value to get the size of the thumb to take that into account.

I'm not sure how you would go about highlighting the thumb, though. I suppose you've tried all the normal things like setting highlighted and/or selected to true, or callingbecomeFirstResponder on the slider?

You might be able to fool the slider into thinking it's being touched by passing all of your UITouch events on to it through the beginTrackingWithTouch:withEvent: method and the other related methods.

Ed Marty
That worked like a charm! Thank you.
carloe
I'm just curious... which part worked like a charm? What approach did you go with?
Ed Marty