views:

33

answers:

2

I'm having a problem refreshing text on a timer. I am displaying the current time and refreshing the screen every second. The problem I'm having is the old time doesn't get erased when the new time gets printed.

Here is the function that displays the current time.

- (void)drawRect:(CGRect)rect {
    CGPoint location = CGPointMake(10,20);
    UIFont *font = [UIFont systemFontOfSize:24.0];
    [[UIColor whiteColor] set];
    NSString *s = [NSString stringWithFormat:@"%@", [NSDate date]];
    [s drawAtPoint:location withFont:font];
}

Here is the timer that refreshes the current time every second:

- (IBAction)startRepeatingTimer {
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    [runloop addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)timerFireMethod:(NSTimer*)theTimer {
    [self setNeedsDisplay];
}

How can I erase the old text or wipe the whole screen clean?

A: 

I found one technique that works.

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(0, 0, 0, 0, 0);
CGContextFillRect(context, rect);
Gattster
+1  A: 

Once you draw text into a context, its no longer text but just another graphical pattern in the bits. You're basically stuck with overwriting the drawn text with the background color. If you have a complex background, you can copy it before drawing the text and then draw the copy in the same position over and over again to erase.

However, you probably shouldn't bother. It's almost always easier and more robust to use an interface element designed to display text such as a label.

TechZen