我需要能够检测键盘上的触摸事件。我有一个应用程序,显示一段时间不活动后发生的屏幕(即没有触摸事件)为了解决这个问题,我已经将我的UIWindow子类化并实现了sendEvent函数,这允许我通过整个应用程序获取触摸事件在一个地方实施该方法。当键盘出现并且用户在键盘上键入时,这种方法无处不在。我需要知道的是,有一种方法可以检测键盘上的触摸事件,就像sendEvent为uiWindow所做的那样。提前谢谢。
答案 0 :(得分: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]; }
无论如何,希望它可以帮助别人。
答案 1 :(得分: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设置为此窗口的委托。并且在appDelegate中定义idleTimeLimitExceeded是我在计时器到期时所做的事情。它们的关键是创建自定义窗口并覆盖sendEvent函数。将此与我在自定义窗口类的init方法中添加的上面显示的两个键盘通知相结合,您应该能够在屏幕上的任何位置获得99%的触摸事件。