简体   繁体   中英

How do I continually display the current time on an iOS app?

I am making a single view application in Xcode that simply updates the time every second in a label. I know how to get the current time (using NSDate ) but where is the method that I would have it refresh in? All that I see in ViewController is the following methods:

- (void)viewDidLoad
- (void)didReceiveMemoryWarning

And all that I see in AppDelegate is the following methods:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions                            
- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application
- (void)applicationWillEnterForeground:(UIApplication *)application
- (void)applicationDidBecomeActive:(UIApplication *)application
- (void)applicationWillTerminate:(UIApplication *)application

To my knowledge, none of these methods look like they are capable of updating the time constantly. I want it to display the time sort of like a clock (it continually updates). How would I do this? I was expecting there to be some kind of loop method to do this in but it doesn't look like there is one.

Try this one :)

 - (void)viewDidLoad
 {
    NSDateFormatter *timeformatter = [[NSDateFormatter alloc] init];
    [timeformatter setTimeStyle: NSDateFormatterShortStyle];
    [timeformatter setDateFormat:@"hh:mm:ss a"];

   [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(UpdateTime:) userInfo:nil repeats:YES];

 }

-(void)UpdateTime:(id)sender
{
   NSString *Time  = [timeformatter stringFromDate:[NSDate date]];
   NSLog(@"Time == %@",Time);
}

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