我需要做同样的事情,所以我最终调整了 UINavigationBar touchesBegan:withEvent 方法,并在调用原始方法之前检查了触摸的 y 坐标。
这意味着当触摸距离我在导航下使用的按钮太近时,我可以取消它。
例如:后退按钮几乎总是捕获触摸事件而不是“第一个”按钮
这是我的类别:
@implementation UINavigationBar (UINavigationBarCategory)
- (void)sTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
float maxY = 0;
for (UITouch *touch in touches) {
float touchY = [touch locationInView:self].y;
if ( [touch locationInView:self].y > maxY) maxY = touchY;
}
NSLog(@"swizzlelichious bar touchY %f", maxY);
if (maxY < 35 )
[self sTouchesEnded:touches withEvent:event];
else
[self touchesCancelled:touches withEvent:event];
}
- (void)sTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
float maxY = 0;
for (UITouch *touch in touches) {
float touchY = [touch locationInView:self].y;
if ( [touch locationInView:self].y > maxY) maxY = touchY;
}
NSLog(@"swizzlelichious bar touchY %f", maxY);
if (maxY < 35 )
[self sTouchesBegan:touches withEvent:event];
else
[self touchesCancelled:touches withEvent:event];
}
来自 CocoaDev 的 Mike Ash 的 swizzle 实现
void Swizzle(Class c, SEL orig, SEL new)
{
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
else
method_exchangeImplementations(origMethod, newMethod);
}
函数调用swizzle函数
Swizzle([UINavigationBar class], @selector(touchesEnded:withEvent:), @selector(sTouchesEnded:withEvent:));
Swizzle([UINavigationBar class], @selector(touchesBegan:withEvent:), @selector(sTouchesBegan:withEvent:));
我不知道 Apple 对此是否满意,这可能违反了他们的 UI 指南,如果在我将应用程序提交到应用商店后,我会尝试更新帖子。