Skip to content

Instantly share code, notes, and snippets.

@macguru
Created September 2, 2016 10:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macguru/22538ba68909cc006135d3ae985eec8b to your computer and use it in GitHub Desktop.
Save macguru/22538ba68909cc006135d3ae985eec8b to your computer and use it in GitHub Desktop.
Tell if a user interaction is currently happening though a touch event in a view's window or something else – like an external keyboard or interaction in a different window (keyboard window). Example use: check if selection change was through touch or external keyboard.
//
// MXSEventTrackingWindow.h
//
// Created by Max Seelemann on 01.09.16.
// Copyright © 2016 The Soulmen. All rights reserved.
//
/*!
@abstract Special window class used for advanced event processing.
*/
@interface MXSEventTrackingWindow : UIWindow
@end
/*!
@abstract Convenience for getting infos about the current application state.
*/
@interface UIView (MXSEventTrackingWindow)
/*!
@abstract Returns if the current event in the view's window is a touch event.
@discussion Also returns NO when there is no current event in the window.
*/
@property(nonatomic, readonly) BOOL currentEventIsTouchEvent;
@end
//
// MXSEventTrackingWindow.m
//
// Created by Max Seelemann on 01.09.16.
// Copyright © 2016 The Soulmen. All rights reserved.
//
#import "MXSEventTrackingWindow.h"
@interface MXSEventTrackingWindow ()
@property(nonatomic, weak, readonly) UIEvent *currentEvent;
@end
@implementation MXSEventTrackingWindow
- (void)sendEvent:(UIEvent *)event
{
_currentEvent = event;
[super sendEvent: event];
_currentEvent = nil;
}
@end
@implementation UIView (MXSEventTrackingWindow)
- (BOOL)currentEventIsTouchEvent
{
if (![self.window isKindOfClass: MXSEventTrackingWindow.class])
return NO;
UIEvent *event = ((MXSEventTrackingWindow *)self.window).currentEvent;
if (!event)
return NO;
return (event.type == UIEventTypeTouches || event.type == UIEventTypePresses);
}
@end
@interface MyTextViewSubclass : UITextView
@end
@implementation MyTextViewSubclass
- (void)setSelectedTextRange:(UITextRange *)selectedTextRange
{
NSLog(@"Selection changed by touch event: %d", self.currentEventIsTouchEvent);
[super setSelectedTextRange: selectedTextRange];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment