c# - 在 iOS Xamarin 中显示秒、分钟和小时的计时器

标签 c# ios timer xamarin.ios xamarin

我正在 Xamarin 中开发 iOS 应用程序。

timer1 = new System.Timers.Timer();
timer1.Interval = 1000;

//Play.TouchUpInside += (sender,e)=>
//{
       timer1.Enabled = true;
       Console.WriteLine("timer started");
       timer1.Elapsed += new ElapsedEventHandler(OnTimeEvent);
//}

这是我在viewdidload()中写的;

public void OnTimeEvent(object source, ElapsedEventArgs e)
{
    count++;
    Console.WriteLine("timer tick");
    if (count == 30)
    {
        timer1.Enabled = false;
        Console.WriteLine("timer finished");

        new System.Threading.Thread(new System.Threading.ThreadStart(() =>
        {
            InvokeOnMainThread(() =>
            {
                StartTimer.Text = Convert.ToString(e.SignalTime.TimeOfDay); // this works!
            });
        })).Start();
    }

    else
    {
        //adjust the UI
        new System.Threading.Thread(new System.Threading.ThreadStart(() =>
        {
            InvokeOnMainThread(() =>
            {
                StartTimer.Text = Convert.ToString(e.SignalTime.TimeOfDay); // this works!
            });
        })).Start();

        timer1.Enabled = false;
        Console.WriteLine("timer stopped");
    }
}

这是我在单击播放按钮时调用的事件。我希望此方法继续运行,以便在 UI 中的标签 (starttimer.Text) 上更新时间。就像我们在 Android 中使用的 Runnable Interface,我们在 iOS 中必须使用什么来保持它运行?

最佳答案

使用异步 - 更干净(没有编码让你再次回到主线程!)

private int _duration = 0;

public async void StartTimer() {
    _duration = 0;

    // tick every second while game is in progress
    while (_GameInProgress) {
        await Task.Delay (1000);
        _duration++;

        string s = TimeSpan.FromSeconds(_duration).ToString(@"mm\:ss");
        btnTime.SetTitle (s, UIControlState.Normal);
    }
}

关于c# - 在 iOS Xamarin 中显示秒、分钟和小时的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29390447/

相关文章:

javascript - 单个 HTML 页面上的多个计时器

c# - 计时器线程进入休眠状态会发生什么

c# - 检测哪种类型的控件处于事件状态

ios - CFNetwork SSLHandshake iOS 9 失败

iphone - 如何使用 NSFileHandle 打开文本文件

ios - 将对齐数组 uint8[8] 转换为 double

python - 我可以在 Python 中同时运行多个计时器吗?

c# - 当代码位于 Form1.Designer.cs 外部时,表格布局面板不会在屏幕上绘制(或工作)

c# - 同一个kinect设备上的多个应用程序

c# - ASP.NET 身份验证问题