textField should update as soon as a method is called
I am working on a project which deals with an examination paper. I display only 1 question at a time on the view. After the users answers the question a second question is displayed if the user swipes towards left hand side.
I have placed a textField to display the score at each point in time. I implemented it but my score gets updated only if the user navigates to the next q开发者_如何学编程uestion. My requirement is that as soon as the question is answered the score should be updated in the textField.
scoreField.text=[NSString stringWithFormat:@"%d",currentScore];
Is there any technique to do so whenever a question is answered? My paper has 20 questions and has 20 submit buttons so I cannot place the above code at each and every submit button action method. It would be ugly and not effective programming.
Please help if there is any way to solve my case.
Thanks in advance
If you understand your problem correctly then you don't want to set scoreField.text
in every submit button handler. I am assuming that you are setting this when navigating to next question. You only need to update this when currentScore
is changed. So I think it's better to create a setter for currentScore
and update scoreField.text
from that. Something like this:
- (void)setCurrentScore:(NSInteger)newScore {
currentScore = newScore;
scoreField.text=[NSString stringWithFormat:@"%d",currentScore];
}
And call setCurrentScore
whenever you need to change the score. Or even better, you can use a setter property and write your own setter implementation.
This can be made really simple, and elegant. With a few assumptions:
- There is globally accessible model object that holds the score, for example
+[Examination sharedExammination]
. - The model object has a KVO (Key-Value-Observing) compatible property like
score
. - You use a custom subclass of
UILabel
to display the score.
With these assumptions you can let your custom UILabel
register for KVO changes to to the score
property and update itself automatically. The implementation of the UILabel
subclass would include something like this:
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[[Examination sharedExamination] addObserver:self
forKeyPath:@"currentScore"
options:0
context:NULL];
}
return self;
}
-(void)dealloc
{
[[Examination sharedExamination] removeObserver:self
forKeyPath:@"currentScore"];
[super dealloc];
}
-(void)observeValueForKeyPath:(NSString*)keyPath
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context
{
if ([keyPath isEqualToString:@"currentScore"]) {
scoreField.text = [NSString stringWithFormat:
@"Score: %d", [object currentScore]];
} else {
[super observerValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
}
}
Try this:
[self.view setNeedsDisplay];
精彩评论