【问题标题】:touchevents not triggering from inside subview触摸事件未从子视图内部触发
【发布时间】:2012-06-25 09:17:48
【问题描述】:

我在尝试通过 UIView 将触摸事件传递给它的附加子视图时遇到了麻烦。

我有许多图像我想做各种事情,所以我有兴趣阅读它们上的触摸事件。在我决定将它们分组到 UIView 之前它工作得很好,所以我猜我需要打开或关闭一些设置以让事件通过。

[TouchImageView.h] -------------------------------------------------------

@interface TouchImageView : UIImageView

[TouchImageView.m] -------------------------------------------------------

- (id)initWithFrame:(CGRect)aRect {
    if (self = [super initWithFrame:aRect]) {
        // We set it here directly for convenience
        // As by default for a UIImageView it is set to NO
        self.userInteractionEnabled = YES;
        state = 0 ;
        rect = aRect ;
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Do what you want here
    NSLog(@"touchesBegan!" );
}

[in my delegate's didFinishLaunchingWithOptions] -------------------------

NSArray *myImages = [NSArray arrayWithObjects:
                     [UIImage imageNamed:@"front-photos.jpg"],
                     [UIImage imageNamed:@"front-films.jpg"],
                     [UIImage imageNamed:@"front-presentations.jpg"],

mainMenuView = [[UIView alloc] init ] ;
mainMenuView.userInteractionEnabled = YES;    // tried setting this to both YES and NO. Same result.
[self.viewController.view addSubview:mainMenuView] ;

myImage = [[TouchImageView alloc] initWithFrame:CGRectMake(0.0f, menuTopHeight, menuButtonWidth, menuButtonHeight)];
[myImage setImage:[myImages objectAtIndex:0]] ;
[mainMenuView addSubview:myImage] ;

谁能告诉我我做错了什么?我在这里看到了很多关于这个主题的类似帖子,但其中大部分是关于设置 userInteractionEnabled(?)

【问题讨论】:

  • 你为什么不使用 UIGesturerecognizer
  • @AlbrahimZ 我不知道一个比另一个更好(?)。认为重载 touchesBegan 将是最简单的解决方案。没想到它不起作用。我对 UIGesturerecognizer 不太熟悉 - 是什么让它成为更好的选择?
  • 手势识别器用于高级手势,因此它们与所有应用程序的行为相同。对于低级控制和识别器不能做的事情,你仍然需要在 touchesbegan、touchesEnded 等中实现逻辑。
  • 所以,你是在告诉我,如果我用手势识别器替换 touchesBegin,那么它不会被子视图阻止?

标签: iphone objective-c uiview event-handling uiimageview


【解决方案1】:

原来我需要为 UIView 定义一个框架。所以我改变了

mainMenuView = [[UIView alloc] init] ;

进入这个:

mainMenuView = [[UIView alloc] initWithFrame:[UIScreen mainScreen] bounds] ;

它又工作了。

【讨论】:

    【解决方案2】:

    首先mainMenuView.userInteractionEnabled = NO;应该是YES UIImageView 也将 userInteractionEnabled 默认设置为 NO,因此您必须将其设置为 YES

    这一行之后

    [mainMenuView addSubview:myImage] ;
    //add
    myImage.userInteractionEnabled = YES;
    

    【讨论】:

    • 我在其构造函数中将其设置为 YES。关于 mainMenuView - 我试过 YES 和 NO,它都不起作用。
    • 对不起,我没有注意到它们,menuTopHeight、menuButtonWidth、menuButtonHeight 的值是多少?
    • 这些值只是图像的尺寸,为了举例,它们可以定义为 0,0,200,200 - 正如我开始提到的那样,事件工作正常,直到我添加它们到 mainMenuView 而不是 self.viewcontroller.view 视图。
    • mainMenuView的frame是什么?
    • 它没有框架 - 显然这是导致它无法触发的原因。一旦我将代码更改为使用 rect 初始化,它就开始工作了 - 谢谢!
    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多