If you really want to set exclusiveTouch
for ALL UIButtons + subclasses in your whole application and not just a single view, you can use method swizzling.
You use the objc runtime to override willMoveToSuperview
and set exclusive touch there.
This is very reliable and i've never had any problems using this technique.
I like doing this especially for UISwitch
, because touch-handling for switches can be a bit tricky and exclusiveTouch
will help avoid bugs caused by simultaneous taps on different switches
Sample taken from the link above and changed so that exclusiveTouch
is set:
#import <objc/runtime.h>
@implementation UIButton (INCButton)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(willMoveToSuperview:);
SEL swizzledSelector = @selector(inc_willMoveToSuperview:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)inc_willMoveToSuperview:(UIView *)newSuperview
{
// This is correct and does not cause an infinite loop!
// See the link for an explanation
[self inc_willMoveToSuperview:newSuperview];
[self setExclusiveTouch:YES];
}
@end
Create a category and insert this code for each class you want to alter.