目标c如何设置整个应用程序的所有UIbutton的独家触摸

我的应用程序有很多button通过应用程序

我想同时将所有的“专属触摸”设置在一起。 或应用程序中的所有视图

我们可以单独设置

[button setExclusiveTouch:YES]; 

但是我想在应用程序中设置所有的button

我们可以设置所有查看独家触摸?

任何机构有任何想法,请build议我。

你可以试试这个

 // Not tested for (UIView * button in [myView subviews]) { if([button isKindOfClass:[UIButton class]]) [((UIButton *)button) setExclusiveTouch:YES]; } 

如果你真的想为整个应用程序中的所有UIButtons +子类设置exclusiveTouch ,而不仅仅是一个单一的视图,你可以使用方法swizzling 。

您可以使用objc运行时来覆盖willMoveToSuperview并在其中设置专属触摸。 这是非常可靠的,我从来没有使用这种技术的任何问题。

我喜欢这样做,尤其是对于UISwitch ,因为对交换机的触摸处理可能有点棘手,并且exclusiveTouch将有助于避免由于同时在不同交换机上同时点击而引起的错误

从上面的链接采取样品,并更改,以便设置exclusiveTouch

 #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 

创build一个类别,并为每个要更改的类插入此代码。

为什么这么难? 做一个类别

 @implementation UIButton (ExclusiveTouch) - (BOOL)isExclusiveTouch { return YES; } @end 
 [[UIButton appearance] setExclusiveTouch:YES]; 

循环遍历最顶层视图的子视图(对于UIButtontypes的每个对象),应用独占触摸