With my iPhone app I need for example a label that is visible for a specified time. How do I manage that?
Showing a label which is for example visible for 10 seconds but is then removed from the view hierarchy?Thanks in advance for your 开发者_开发技巧help! :)
Show the label, and then start an NSTimer
, whose timeout callback method hides the label. (I'm hiding the label instead of removing it from the view hierarchy, which may or may not be more appropriate.)
Code is similar to my answer from NSTimers and triggers in Obj-C
MyViewController.h:
...
@interface MyViewController : UIViewController
{
...
UILabel* label;
NSTimer* timer;
...
}
...
MyViewController.m:
...
static const NSTimeInterval TIMER_INTERVAL = 10.0;
...
- (void)dealloc
{
[self stopTimer];
...
[super dealloc];
}
...
- (void)showLabelAndStartTimer
{
label.hidden = NO;
[self startTimer];
}
...
- (void)startTimer
{
[self stopTimer];
timer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL
target:self
selector:@selector(timerCallback)
userInfo:nil
repeats:NO];
[timer retain];
}
...
- (void)stopTimer
{
if (timer)
{
[timer invalidate];
[timer release];
timer = nil;
}
}
...
- (void)timerCallback
{
label.hidden = YES;
}
Put this in viewWillAppear
:
[self performSelector:@selector(hideLabel) withObject:nil afterDelay:0.0];
And in hideLabel
, hide your label, like this:
-(void)hideLabel {
yourLabel.hidden=YES;
}
Specify time according to you at afterDelay:0.0
at this place.
精彩评论