Sau*_*ank 4 objective-c xamarin.ios ios
我是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");
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我将其转换为c#.
实现这一点肯定有更好的方法,但让我们对这段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
{
}
Run Code Online (Sandbox Code Playgroud)
注意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");
}
}
Run Code Online (Sandbox Code Playgroud)
我换成maxIdleTime了TimeSpan.FromHours (1).否则,你将拥有与Obj-C相同的行为,包括bug(如果有的话)(虽然它看起来不错).