如何在应用程序的每个视图中捕获触摸事件?

问题描述 投票:0回答:4

我想在我的所有视图中捕获触摸事件。所以它应该处理

appdelegate

我提到了

iPhone:检测自上次屏幕触摸以来用户不活动/空闲时间

但没有成功

希望我能朝着正确的方向前进

谢谢

iphone events touch
4个回答
0
投票

应用程序委托不是响应者。我将子类化 UIWindow,并重写它的事件处理方法,因为窗口会在第一时间获取所有触摸事件。


0
投票

与 futureelilte7 所说的相反,您的应用程序委托(在创建项目时生成)实际上是 UIResponder 的子类,并响应选择器

touchesBegan:withEvent:
和其他类似的选择器。

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    // your code here
}

这应该保留默认的触摸行为,并让您有机会执行自己的自定义功能。


0
投票

无需子类化 UIWindow,这里有简单的直通手势示例代码,捕获所有视图的所有触摸:

有一种方法可以在整个应用程序范围内运行此应用程序,而无需单个控制器执行任何操作。只需添加一个不会取消触摸的手势识别器即可。这样,计时器将跟踪所有触摸,并且其他触摸和手势根本不受影响,因此其他人不必知道它。

fileprivate var timer ... //timer logic here

@objc public class CatchAllGesture : UIGestureRecognizer {
    override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
    }
    override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        //reset your timer here
        state = .failed
        super.touchesEnded(touches, with: event)
    }
    override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesMoved(touches, with: event)
    }
}

@objc extension YOURAPPAppDelegate {

    func addGesture () {
        let aGesture = CatchAllGesture(target: nil, action: nil)
        aGesture.cancelsTouchesInView = false
        self.window.addGestureRecognizer(aGesture)
    }
}

在您的应用程序委托的 did finish 启动方法中,只需调用 addGesture 即可完成设置。所有触摸都将通过 CatchAllGesture 的方法,而不会妨碍其他功能。

https://stackoverflow.com/a/45496010/199966


-1
投票

只需实施

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

UITouch *touch = [[event allTouches] anyObject];

CGPoint touchLocation = [touch locationInView:self.view];

//your logic

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{ 

//your logic

}  


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

{

//your logic

}

在你的代码中..我认为其余的你可以弄清楚。

© www.soinside.com 2019 - 2024. All rights reserved.