我正在 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/