A running stopwatch
October 2, 2009
Nothing is ever as simple as it seems. I figured I would be able to create a Timer, hook into an event off of that timer and do some work i.e. display the time on the screen. Boy howdy did that not turn out to be the case. I had to learn a few things to get it working.
One important bit is about selectors. From what I can determine, selectors are pointers to delegates. You create a selector and give it a name of an exported method, in this way it can be passed to things like event loops or timers in our case. Another tidbit is that if you see references to ‘self’ in samples for objective c code it maps to ‘this’ in c#. Obvious to some but something that caused me a bit of a lightbulb moment.
Hopefully the code speaks for itself. I haven’t refactored yet but I haven’t exactly done any TDD during this development cycle so I’m not too worried about it. That said, if you see anything that needs improvement please let me know!
public partial class AppDelegate : UIApplicationDelegate
{
bool isRunning = false;
DateTime start, end = new DateTime();
TimeSpan ts = new TimeSpan(0,0,0,0,5);
private static Selector selector = new Selector("UpdateTimer");
// This method is invoked when the application has loaded its UI and its ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
button.TouchDown += ButtonPushed;
// Create timer
// notes: the timer starts immediately
// selector is the delegate we want to run when the timer fires
NSTimer.CreateScheduledTimer(0.01, this, selector, null, true);
window.MakeKeyAndVisible ();
return true;
}
[Export ("UpdateTimer")]
public void UpdateTimer()
{
string time;
DateTime increment;
if (isRunning)
{
increment = DateTime.Now;
ts = increment.Subtract(start);
time = string.Format("{0}:{1}", ts.Seconds, ts.Milliseconds);
display.Text = time;
// Console.WriteLine(time);
}
}
public void ButtonPushed(object sender, EventArgs e)
{
if (isRunning)
{
end = DateTime.Now;
isRunning = false;
button.SetTitle("Start", UIControlState.Normal);
ts = end.Subtract(start);
display.Text = string.Format("{0}:{1}", ts.Seconds, ts.Milliseconds);
}
else
{
start = DateTime.Now;
isRunning = true;
button.SetTitle("Stop", UIControlState.Normal);
}
}
}
I did demo the running app to my girlfriend so my weekly demo requirement is complete. Onward to the next cards…
October 5, 2009 at 11:44 pm
MonoTouch Article – Mauja – Part 3 – Stopwatch Game – A Running Game…
Thank you for submitting this entry – Trackback from MonoTouch.Info…