How to respond to touch events in UIWindow?

前端 未结 4 1012
不思量自难忘°
不思量自难忘° 2020-12-30 14:11

Is it possible to handle touch events in the key UIWindow in the app Delegate or anywhere else?

Any help would be appreciated please.

4条回答
  •  抹茶落季
    2020-12-30 14:50

    You will have to subclass UIWindow with your own class and override sendEvent: method. But remember that the method gets other types of events - not only touches so you have to check for event type (event.type == UIEventTypeTouches). Also since you get set of touches you might want to check which ones just began, which ones ended, moved etc. To do that you have to iterate through allTouches and check the phase property of every UITouch.

    @implementation TouchWindow
    
    - (void)sendEvent:(UIEvent *)event {
    
        if (event.type == UIEventTypeTouches) {
            for(UITouch * t in [event allTouches]) {
                if(t.phase == UITouchPhaseBegan) {
                    /*
                    Paste your code here. 
                    Inform objects that some touch has occurred. 
                    It's your choice if you want to perform method/selector directly, 
                    use protocols/delegates, notification center or sth else. 
                    */
                }
            }
        }
    
        [super sendEvent:event];
    }
    
    @end

    Of course TouchWindow is subclass of UIWindow

    @interface TouchWindow : UIWindow 
    @end
    

    And you will probably have to change that class in your .xib file in XCode

提交回复
热议问题