How do I update a UISlider’s value property after its minimum and maximumValues have been changed (during runtime)?
Consider the following Code:
1 UILabel hooked up to an IBOutlet – label
1 UISlider (default Settings min=0, max=1) hooked up to an IBOutlet – slider and an IBAction – valueChanged
1 Button hooked up to an IBAction – buttonTouch
and the following two IBAction implementations:
- (IBAction)valueChanged:(id)sender {
label.text=[NSString stringWithFormat:@"%f",slider.value];
}
- (IBAction)buttonTouch:(id)sender {
slider.maximumValue=4;
slider.minimumValue=2;
label.text=[NSString stringWithFormat:@"%f",slider.value];
}
When I move the slider to a certain position it get’s updated correctly.
However, when I change the Sliders’s minimum and maximumValues by triggering the buttonTouch IBAction the slider.value property doesn’t change – it still shows the old value (between 0 and 1). So changing the minimum and maximum properties doesn’t have a direct effect on the value property.
Before:
min=0 value=0.5 max=1
After:
min=2 value=0.5 max=4
This is supposed to be 3!
I guess you could calculate the new value based on your knowledge of the value, min and max for the old setting and min and max for the new setting, but that doesn’t seem to be a nice solution (see formula below)
newValue = oldvalue / (oldmax - oldmin) * (newmax - newmin) + newmin
You should update the value manually. UIKit can not and do not make any guess as to what to do with the value when the min and max limits changes.
Should it be truncated at the edges? Should it be a close approximation within the new range? There are many more possible solutions but the one you desire for this particular case. UIKit makes the sane choice of making no choice, and instead leave it up to you to tell what to do.
There is also a golden rule (with a few exceptions) that changing one property should not affect another property. Only action methods are allowed to change more than one state. Perhaps you should add your own method as a category:
-(void)[UISlider setMinimumValue:(CGFloat)maximumValue:(CGFloat)adjustingValueForNewRange:(BOOL)].