简体   繁体   中英

set NSTimer time to NavigationBar label

I want to display remaining time from my NSTimer in NavigationItem title, that's why I can't create outlet for it.
My code is from this question NSTimer problem :

@interface MyController : UIViewController
{
UILabel * theLabel;

@private
NSTimer * countdownTimer;
NSUInteger remainingTicks;
}

@property (nonatomic, retain) IBOutlet UILabel * theLabel;

-(IBAction)doCountdown: (id)sender;

-(void)handleTimerTick;

-(void)updateLabel;

@end

@implementation MyController
@synthesize theLabel;

-(IBAction)doCountdown: (id)sender
{
  if (countdownTimer)
  return;


remainingTicks = 60;
[self updateLabel];

countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(handleTimerTick) userInfo: nil repeats: YES];
}

-(void)handleTimerTick
{
remainingTicks--;
[self updateLabel];

if (remainingTicks <= 0) {
  [countdownTimer invalidate];
  countdownTimer = nil;
  }
}

-(void)updateLabel
{
  theLabel.text = [[NSNumber numberWithUnsignedInt: remainingTicks] stringValue];
}


@end

So, how can I put theLabel.text to label in NavigationBar ?
I call method doCountdown in viewDidLoad :

[self doCountdown:nil];

Where is my fault? If I try to watch theLabel, NSLog says (null) .

UPD: And another stupid question. If I try to move label with NSTimer to the right, like here:

[self.navigationItem setTitle:@"Экзамен"]; self.theLabel = [[UILabel alloc] init]; [self doCountdown:nil]; UILabel *yourLabel = [[UILabel alloc]initWithFrame:CGRectMake(260,6,55,32)]; yourLabel.text = self.theLabel.text; [self.navigationController.navigationBar addSubview:yourLabel]; my timer doesn't start, it shows initial time at label and nothing more.

The label is null because you don't create it anywhere.

In your viewDidLoad you should create it and add to navigation item's title view, eg like this:

self.theLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)] autorelease];
self.navigationItem.titleView = self.theLabel;

Don't forget to release theLabel in dealloc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM