2

我需要能够检测键盘上的触摸事件。我有一个应用程序,它显示在一段时间不活动(即没有触摸事件)后出现的屏幕为了解决这个问题,我将我的 UIWindow 子类化并实现了 sendEvent 函数,它允许我通过以下方式获取整个应用程序的触摸事件在一个地方实施该方法。除了出现键盘并且用户在键盘上打字时,这在任何地方都有效。我需要知道的是有没有一种方法可以检测键盘上的触摸事件,有点像 sendEvent 对 uiWindow 所做的。提前致谢。

4

2 回答 2

4

找到了解决问题的方法。如果您观察到以下通知,则可以在按下该键时获得一个事件。我在我的自定义 uiwindow 类中添加了这些通知,因此在一个地方执行此操作将允许我在整个应用程序中获取这些触摸事件。

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];

- (void)keyPressed:(NSNotification*)notification
{  [self resetIdleTimer];  }

无论如何,希望它可以帮助别人。

于 2010-08-10T14:21:40.150 回答
0

iPhoneDev:这就是我正在做的事情。

我有一个自定义 UIWindow 对象。在这个对象中,有一个 NSTimer,只要有触摸就会重置。要获得这种感觉,您必须重写 UIWindow 的 sendEvent 方法。

这就是我的自定义窗口类中 sendEvent 方法的样子:

- (void)sendEvent:(UIEvent *)event
{
    if([super respondsToSelector: @selector(sendEvent:)])
    {
      [super sendEvent:event];
    }
    else
    {   
        NSLog(@"%@", @"CUSTOM_Window super does NOT respond to selector sendEvent:!");  
        ASSERT(false);
     }

     // 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)
     {
        // anyObject works here.
        UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
        if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
        {
           [self resetIdleTimer];
        }
     }
}

这是resetIdleTimer:

- (void)resetIdleTimer 
{
    if (self.idleTimer)
    {
        [self.idleTimer invalidate];
    }
    self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:PASSWORD_TIMEOUT_INTERVAL target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO];
}

在此之后,在 idleTimerExceeded 中,我向窗口委托(在本例中为 appDelegate)发送一条消息。

- (void)idleTimerExceeded
{
    [MY_CUSTOM_WINDOW_Delegate idleTimeLimitExceeded];
}

当我在 appDelegate 中创建这个自定义窗口对象时,我将 appDelegate 设置为这个窗口的委托。在 idleTimeLimitExceeded 的 appDelegate 定义中,我在计时器到期时执行我必须做的事情。他们的关键是创建自定义窗口并覆盖 sendEvent 函数。结合上面我在自定义窗口类的 init 方法中添加的两个键盘通知,您应该能够在应用程序的任何位置获得屏幕上 99% 的所有触摸事件。

于 2010-11-30T19:05:32.080 回答