In our last episode, we created a new project in Xamarin Studio, created a custom view controller, initialized its view, and added a clock view. Today, we will explore several ways to display and update the time.

Display the Current Time

To display the current time, add a method to the class CurrentWeatherClockViewController to update the clock view:

A shortcut for entering this method is to first type override. As soon as you type a space after override, Xamarin Studio will provide a completion list. Choose ViewWillAppear from that list. The IDE will then automatically insert a skeleton of the ViewWillAppear method, including the call to base.ViewWillAppear. All you have to do is add this line:

this.UpdateClockView ();

When you build and run the project, your app will display the current time. But the time is still not being updated like a real clock. Let’s do that now.

Update the Current Time

To update the time, we need a timer. Add a private field:

private NSTimer timer;

Note that the IDE sets NSTimer in red. Right click and choose Resolve > using MonoTouch.Foundation.

It’s a good idea to stop timers, tasks, and other continuously running resources that a page is using when the user navigates away.

Timer Periodicity

Let’s take an informal look at whether our timer really is firing at a one second interval. Change the clock display format:

timeLabel.Text = String.Format ("{0:hh:mm:ss.ff}", DateTime.Now);

Build and run. In my experiments, it looks pretty good on both the simulator and an iPhone device. However, let’s not take any chances. A common technique, when sampling a continuous fuction is to sample at twice the frequency1. The clock is not a true continuous function, but appears to be from our persepctive of displaying samples once per second.

Change the timer interval rate to one half second, then build and run again. Note that the clock is updated approximately every half second.

Cross-Platform Timer

This timer works fine, but when using Xamarin and C#, we’d like to use the .Net libraries where we can. This makes the app more cross-platform in case we wish to port to Android later. Of course, Android does not have a UIViewController, so that will have to change anyway. But in a larger application, you likely would have implemented the timer in a separate class that could be cross-platform.