2012-06-25 133 views
1

我遇到了一些麻烦,试图通过UIView获取触摸事件给它所附的子视图。touchevents不会从子视图内触发

我有很多图片我想做各种各样的东西,所以我有兴趣阅读它们上的触摸事件。它工作得很好,直到我决定将它们分组到一个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(?)

+0

你为什么不使用UIGesturerecognizer – self

+0

@AlbrahimZ我不知道一个比另一个更好(?)。认为过载touchesBegan将是最简单的解决方案。没想到它不行。我对UIGesturerecognizer并不熟悉 - 是什么让它成为更好的选择? – Frederik

+0

手势识别器适用于高级手势,因此它们的行为与所有应用程序相同。对于低级别的控制和做的事情,识别器不能你将仍然必须实现touchesbegan,touchesEnded等逻辑 – self

回答

1

事实证明,我需要定义了UIView一帧之后。因此,我改变

mainMenuView = [[UIView alloc] init] ; 

到这一点:

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

并再次合作。

0

所有mainMenuView.userInteractionEnabled = NO;首先应该是YESUIImageViewuserInteractionEnabled设置为NO由deafult,所以你将必须把它设置为YES

此线

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

我在其构造函数中将其设置为YES。关于mainMenuView - 我已经尝试了YES和NO,它不能工作。 – Frederik

+0

对不起,我没有注意到它们,menuTopHeight,menuButtonWidth,menuButtonHeight的值是什么? –

+0

这些值只是图像的尺寸,为了示例的目的,它们可以定义为0,0,200,200 - 正如我刚才提到的,事件工作正常,直到我将它们添加到mainMenuView而不是自己.viewcontroller.view视图。 – Frederik