简体   繁体   中英

How do I trigger an event X seconds after a button has been clicked in a Xamarian iOS application?

I am teaching myself C# and, as part of this, am trying to develop an iOS countdown timer app that is to play a .wav sound file X seconds after a timer initiating button has been clicked as the timer value has gone from X to 0.

In an attempt to do this I have tried using the System.Timers namespace but have been unable to figure out how to program the countdown timer described above. Below is my incomplete code (code that obviously does not fulfill the above described function but might be a part of the full code that would fulfill that function):

partial void UIButton1416_TouchUpInside(UIButton sender)
{
  url = NSUrl.FromFilename("Sounds/bell.wav");
  bell = new SystemSound(url);

  int RoundedTimerValue = Convert.ToInt32(Math.Round(TimerSlider.Value, 0));

  System.Timers.Timer timer = new System.Timers.Timer();
  timer.Interval = 60000;
  timer.Enabled = true;
}

Does anyone know how to create the described countdown timer / Trigger an event X seconds after a button has been clicked?

Example Code.

Timer timer = new Timer();
        timer.Interval = 60000;
                    timer.Elapsed += new ElapsedEventHandler((x,y) => {
                    //Do whatever you want
                    timer.Stop();
            });

Put the below code in the Button Click Handler and make the timer variable global.

  timer.Start();

Or you can leave everything in the Button's click handler, not a big deal.

Explanation: The timer class has an event called Elapsed which is called when the specified number of milliseconds in the timer's Interval gets over. with the line

timer.Elapsed += new ElapsedEventHandler((x,y) => {...

we are assigning a Delegate(Virtual function) to be called when the timer is up. therefore any code within the braces{} will be called at every Timer.Interval milliseconds. we stop the timer at that time as we don't want it to keep running and generate a lot of events.

Update 2:

Normally , EventHandlers are Defined using

return_type functionName(object sender, EventArgs e);

But since the delegate is virtual, so is the parameter. x corresponds to sender and y corresponds to e .

that event handler code can also be written as below

void someFunction(object sender, ElapsedEventArgs e)
{
   timer.Stop();
}

and then,

timer.Elapsed += new ElapsedEventHandler(someFunction);

As for the '=>' you can read about Lambda Expressions Here

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