【问题标题】:iPhone - how to track touches and allow button taps at the same time?iPhone - 如何同时跟踪触摸并允许点击按钮?
【发布时间】:2024-01-12 20:10:01
【问题描述】:

我想知道如何跟踪 iPhone 屏幕上任意位置的触摸,并且仍然让 UIButton 响应点击。

我对 UIView 进行了子类化,使其成为全屏视图和层次结构中的最高视图,并覆盖了它的 pointInside:withEvent 方法。如果我返回 YES,我可以跟踪屏幕上任何地方的触摸,但按钮没有响应(可能是因为视图被指示处理和终止触摸)。如果我返回 NO,则触摸会通过视图并且按钮会响应,但我无法跟踪触摸。

我需要子类化 UIButton 还是可以通过响应者链实现?我做错了什么?

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    return NO;
}   

//only works if pointInside:withEvent: returns YES.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        NSLog(@"began");    
        [self.nextResponder touchesBegan:touches withEvent:event];
}

//only works if pointInside:withEvent: returns YES.
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
        NSLog(@"end");      
        [self.nextResponder touchesEnded:touches withEvent:event];
}

【问题讨论】:

    标签: iphone uibutton uitouch


    【解决方案1】:

    而不是拥有额外的视图,您可以子类化您的应用程序主窗口并跟踪触摸(以及其中的其他事件)

    @interface MyAppWindow : UIWindow
    ...
    @implementation MyAppWindow
    
    - (void)sendEvent:(UIEvent*)event {
        [super sendEvent:event];
    
        if (event.type == UIEventTypeTouches){
             // Do something here
        }
       return;  
    }
    

    然后将您的应用程序窗口类型设置为 MyAppWindow(我在 IB 的 MainWindow.xib 中这样做了)

    【讨论】:

    • 谢谢,这是一个很好的开始。我已成功开始跟踪窗口中的触摸,但想将一组触摸传递给视图控制器以处理触摸事件。我需要@class视图还是什么?代码,如果有人感兴趣:pastie.org/924485
    • 得到了我正在寻找的行为。我将我想要的视图添加到代理中,代理将它们添加到加载的窗口中。我在子类窗口中创建了视图控制器的@class,这样当窗口注册触摸事件时,我可以控制视图的属性。