4

我是 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#。

4

1 回答 1

8

Obj-C当然有更好的方法来实现这一点,但是让我们对此代码进行几乎逐行的翻译Xamarin.iOS C#

sendEvent是一种方法UIApplication。对它进行子类化非常少见,请参阅UIApplication 类参考上的子类化注释

一旦你对它进行子类化,你必须指示运行时使用它,这是在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");
    }
}

我换成maxIdleTimeTimeSpan.FromHours (1)。否则,您将拥有与 Obj-C 相同的行为,包括错误(如果有)(但看起来还不错)。

于 2013-11-12T14:24:29.540 回答