全局检测触摸

4

我想解决这个(相对)简单的问题,但是我失败了,所以我真的需要你的建议。

我的应用程序由一个uitabbar和几个选项卡组成。其中一个选项卡中有一堆UIImageView,每个UIImageView代表一张图片的缩略图。类似于通过长按应用程序图标从iPhone中删除应用程序一样,我实现了UILongPressGestureRecognizer识别器,它开始摇晃拇指。如果用户点击拇指角上出现的“X”,则会删除图片。

启动和停止摇晃动画的逻辑在UIImageView的子类中,该子类用于显示缩略图。

我正在尝试做的是,如果用户在拇指之外的任何其他地方按下,则取消晃动效果。如果可能的话,最好将检测此取消触摸的代码放置在UIImageView子类中。

2个回答

6
为了全局捕获所有的触摸事件,我最终采用了以下方式来子类化UIWindow:
//  CustomUIWindow.h
#import <UIKit/UIKit.h>

#define kTouchPhaseBeganCustomNotification @"TouchPhaseBeganCustomNotification"

@interface CustomUIWindow : UIWindow
@property (nonatomic, assign) BOOL enableTouchNotifications;
@end

//  CustomUIWindow.m
#import "CustomUIWindow.h"

@implementation CustomUIWindow

@synthesize enableTouchNotifications = enableTouchNotifications_;

- (void)sendEvent:(UIEvent *)event
{
    [super sendEvent:event];  // Apple says you must always call this!

    if (self.enableTouchNotification) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kTouchPhaseBeganCustomNotification object:event];
    }
}@end

每当我需要全局监听所有触摸事件时,我会执行以下操作:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(stopThumbnailWobble:)
                                             name:kTouchPhaseBeganCustomNotification
                                           object:nil];

((CustomUIWindow *)self.window).enableTouchNotification = YES;   

在stopThumbnailWobble方法中,我移除了观察者,并处理UITouch事件以决定是否移除缩略图:
- (void)stopThumbnailWobble:(NSNotification *)event
{    
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:kTouchPhaseBeganCustomNotification 
                                                  object:nil];
    ((CustomUIWindow *)self.window).enableTouchNotification = NO;

    UIEvent *touchEvent = event.object;
    // process touchEvent and decide what to do
    ...

希望这能帮助其他人。

我的应用程序崩溃并显示以下错误信息:[UIWindow setEnableTouchNotifications:]: 无法识别的选择器发送到实例 - Kanan Vora
你有继承UIWindow吗? - Tomas Camin
不,我已经将其删除了,因为我的问题通过其他方式得到解决。无论如何,谢谢你。至少我知道UIWindow是这样子类化的。 - Kanan Vora
.enableTouchNotification(s)不匹配存在问题,应该会给编译器警告。但仍然是有用的答案,谢谢。 - Clay Bridges

0
如果您必须在您的uiimageview子类中包含代码检测,那么我会告诉appdelegate收到了触摸和位置。然后,appdelegate可以告诉所有的uiimageviews或告诉viewcontroller,然后再告诉它的uiimageviews。
未经测试的代码:
appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate touchedAt:(int)xPos yPos:(int)yPos];

实际上,我正在寻找一种通知观察方式,可以从uiimageview代码中激活,以验证触摸是否在uiimageview内部或外部。在uiimageview之外的触摸将取消晃动效果。 - Tomas Camin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接