有没有办法在iPhone上通过触摸?

Ed *_*rty 23 iphone cocoa-touch

我有几个UIButton用于在主区域中点击时设置当前操作的s.我还想让用户直接从按钮拖动到主区域并采取相同的动作; 实质上,touchesBegan和touchesMoved应该在触摸UIButtons时传递到主视图,但也应该发送按钮按下动作.

现在,我在内部修改控制.拖动出口调用内部部分设置控件,然后调用触摸开始部分启动主区域触摸操作.

但是,此时,touchesMoved和touchesEnded显然没有被调用,因为触摸起源于UIButton.

有没有办法半忽略触摸所以它们被传递到主区域,但也允许我先设置控件?

dav*_*Mac 36

我知道这个问题已经两年了(已经回答了),但是......

当我自己尝试这个时,触摸被转发,但按钮不再像按钮那样.我也通过了"超级"的接触,现在一切都很顺利.

因此,对于可能偶然发现的初学者来说,这就是代码应该是这样的:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  
    [super touchesBegan:touches withEvent:event];
    [self.nextResponder touchesBegan:touches withEvent:event]; 
}
Run Code Online (Sandbox Code Playgroud)

  • 这种方法会在UIButton的子类中吗? (2认同)

Pax*_*xic 25

在文档中,查找响应程序对象和响应程序链

您可以通过转发响应链上的触摸来"共享"对象之间的触摸.你的UIButton有一个接收UITouch事件的响应者/控制器,我的猜测是,一旦它对它返回的消息进行了解释 - 触摸已被处理和处理.

Apple建议这样的事情(基于触摸的类型):

[self.nextResponder touchesBegan:touches withEvent:event];

传递的不是处理触摸事件.

子类UIButton:

MyButton.h

#import <Foundation/Foundation.h>

@interface MyButton : UIButton {

}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event ;

@end
Run Code Online (Sandbox Code Playgroud)

MyButton.m

#import "MyButton.h"

@implementation MyButton

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  
    printf("MyButton touch Began\n");
    [self.nextResponder touchesBegan:touches withEvent:event]; 
}
@end
Run Code Online (Sandbox Code Playgroud)

  • 没有必要在标题中声明touchesBegan :: method,因为它只是被覆盖了,对吧? (3认同)
  • 恐怕我不太明白如何从 UIButton 捕获消息并将它们传递给 UIView 而不将 UIButton 子类化以实际获取消息。 (2认同)
  • 您在文档上方有一个链接.我一直遇到同样的问题,只是阅读这些文档:"如果你实现一个自定义视图来处理事件或动作消息,你不应该直接将事件或消息转发到nextResponder以将其发送到响应者链.而是调用当前事件处理方法的超类实现 - 让UIKit处理响应者链的遍历." (2认同)

小智 17

不需要子类化!在其他任何事情之前,只需将其放在实现的顶部:

#pragma mark PassTouch

@interface UIButton (PassTouch)
@end

@implementation UIButton (PassTouch)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.nextResponder touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    [self.nextResponder touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    [self.nextResponder touchesEnded:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    [self.nextResponder touchesCancelled:touches withEvent:event];
}
@end
Run Code Online (Sandbox Code Playgroud)

  • BTW可能仍然需要子类.例如,如果您需要混合需要在同一视图中传递触摸的按钮,而按钮由于某种原因您不希望具有该功能,该怎么办?当我第一次尝试这个时,我在UIButton上创建了一个类别,但发现由于我上面提到的原因,使用子类更安全所以我确切地知道我何时使用了一个转发触摸的按钮. (3认同)
  • 我不建议这样做.如果首先调用类别方法或默认方法,则无法保证.这可能有效但它也意味着你项目中的每个'UIButton'都有可能克隆这种行为(没有控制). (2认同)