Slider / Text Box Exchange Data
I have a UISlider
that has two text boxes attached to it. Think of it like a tip calculator. Think about a receipt: it has a spot for you to put the tip, and then the final value. Let's add a slider into the mix.
So now we have two text fields (tip percentage and tip amount) and the slider. When the slider moves it calls a method that updates the two text boxes according to the value that the person has selected with the slider.
[self.slider addTarget:self
action:@selector(sliderValueChanged:)
forControlEvents:UIControlEventValueChanged];
-(void)sliderValueChanged:(id)sender
{
tipPercent.text = [NSString stringWithFormat:@"%d", (int)slider.value];
tipPercentDbl = (int)slider.value;//tipPercent as Dbl
tipDbl = (totalDbl * (tipPe开发者_如何学GorcentDbl/100));//tip as Dbl
tip.text = [NSString stringWithFormat:@"%.2f", tipDbl];
tipPercent.text = [NSString stringWithFormat:@"%.0f", tipPercentDbl];
totalWithTipDbl = (totalDbl+tipDbl);
totalWithTip.text = [NSString stringWithFormat:@"%.2f", totalWithTipDbl];
}
This works perfectly. What I want to do now (and am having trouble figuring it out) is how to change the value when the text fields are changed. i.e. someone manually enters in their own tip, how to update the slider and the tip percentage; or if someone manually enters in a tip percentage, how to update the slider and the tip value.
What would be the best way to do this?
This is fairly easy. I don't know all the variables you used, so substitute your own when you try the code. When the keyboard resigns, call the method:
- (void)updateTheSliderAndTipPercentage; {
float percentage = tipTheyEntered / totalCost;
[slider setValue:percentage animated:YES];
percentage *= 100; // This is if you want the percentage in [0,100].
tipPercent.text = [NSString stringWithFormat:@"%f", percentage];
}
EDIT: In order to know when you call this method, simple check:
- (BOOL)textFieldShouldReturn:(UITextField *)textField; {
if(textField == tipTheyEnteredTextField){
[self updateTheSliderAndTipPercentage];
}
}
Hope that helps!
精彩评论