In the online Stanford CS193p iPhone Application Development course, lecture 6, an application is built which has a slider as input and a custom view as output.
When the slider is changed, the view controller sets the slider value again.
Important bits of the view controller in Happiness 2.zip:
@implementation HappinessViewController
@synthesize happiness;
- (void)updateUI
{
// assignment-loop when called from happinessChanged:?
self.slider.value = self.happiness; // sets slider to model's (corrected) value
[self.faceView setNeedsDisplay];
}
- (void)setHappiness:(int)newHappiness
{
if (newHappiness < 0) newHappiness = 0; // limit value
if (newHappiness > 100) newHappiness = 100;
happiness = newHappiness;
[self updateUI]; // changed happiness should update view开发者_JS百科
}
- (IBAction)happinessChanged:(UISlider *)sender // called by changed slider
{
self.happiness = sender.value; // calls setter setHappiness:
}
Doesn't this result in a loop (slider changed -> model updated -> change slider -> ?)?
Or is this even good practice?
If the slider is updated from code, rather than by the user, it presumably doesn't sent the valueChanged action. So you don't get an infinite loop.
This can be used to "correct" the value selected by the user, or to force the slider onto regular tick marks instead of a smooth scale.
精彩评论