我是iOS开发新手,我使用monotouch开发iOS应用程序,我想知道自应用程序空闲以来的时间,我得到了ObjC代码但无法将其转换为c#。 这是代码:
- (void)sendEvent:(UIEvent *)event {
[super sendEvent:event];
// Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
// allTouches count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
}
- (void)resetIdleTimer {
if (idleTimer) {
[idleTimer invalidate];
[idleTimer release];
}
idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}
- (void)idleTimerExceeded {
NSLog(@"idle time exceeded");
}
任何人都可以帮助我将其转换为c#。
答案 0 :(得分:8)
当然有更好的方法来实现这一目标,但让这个Obj-C
代码到Xamarin.iOS
C#
进行几乎逐行转换:
sendEvent
是UIApplication
的一种方法。将它子类化是非常罕见的,请参阅UIApplication class reference上的子类化注释
一旦将其子类化,就必须指示运行时使用它,这是通过Main
方法完成的,通常在Main.cs
中找到。以下是修改后的Main.cs
现在的样子。
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
UIApplication.Main (args, "MyApplication", "AppDelegate");
}
}
[Register ("MyApplication")]
public class MyApplication : UIApplication
{
}
注意类的Register
属性,用作UIApplication.Main
的第二个参数。
现在,让我们将您的代码翻译成真实的:
[Register ("MyApplication")]
public class MyApplication : UIApplication
{
public override void SendEvent (UIEvent uievent)
{
base.SendEvent (uievent);
var allTouches = uievent.AllTouches;
if (allTouches.Count > 0) {
var phase = ((UITouch)allTouches.AnyObject).Phase;
if (phase == UITouchPhase.Began || phase == UITouchPhase.Ended)
ResetIdleTimer ();
}
}
NSTimer idleTimer;
void ResetIdleTimer ()
{
if (idleTimer != null) {
idleTimer.Invalidate ();
idleTimer.Release ();
}
idleTimer = NSTimer.CreateScheduledTimer (TimeSpan.FromHours (1), TimerExceeded);
}
void TimerExceeded ()
{
Debug.WriteLine ("idle time exceeded");
}
}
我将maxIdleTime
替换为TimeSpan.FromHours (1)
。否则,你将拥有与Obj-C相同的行为,包括bug(如果有的话)(虽然看起来不错)。