我有一个视图,在该视图中我添加了UITapGesture
。现在,当我在视图中放置一个按钮并单击按钮时,它不会调用按钮操作。
这是我的代码:
ButtionView=[[UIView alloc]initWithFrame:CGRectMake(x, y, 84, 84)];
ButtionView.tag=i;
UIImageView *coverImageView = [[UIImageView alloc]
initWithFrame:CGRectMake(0,0,ButtionView.frame.size.width,84)];
coverImageView.tag = i;
UIButton *notesbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
notesbutton.frame=CGRectMake(0, 0,20,20);
notesbutton.tag=i;
[notesbutton addTarget:self action:@selector(buttonClickedForNotes:)
forControlEvents:UIControlEventTouchUpInside];
[ButtionView addSubview:coverImageView];
[ButtionView addSubview:notesbutton];
[notesbutton bringSubviewToFront:ButtionView];
[self.scrollview addSubview:ButtionView];
[ButtionView addGestureRecognizer:oneFingerSingleTap];
-(IBAction)buttonClickedForNotes:(id) sender
{
NSLog(@"buttion action call");
}
答案 0 :(得分:2)
首先,订阅UITapGesture的代表。
[singleTapGestureRecognizer setDelegate:self];
然后你必须把这个按钮变成你所在班级的ivar。 然后,将此方法添加到您的班级:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
// Check if the touch was on the button. If it was,
// don't have the gesture recognizer intercept the touch
if (CGRectContainsPoint(notesButton.frame, [touch locationInView:self.view]))
return NO;
return YES;
}
希望这会有所帮助。
答案 1 :(得分:1)
默认情况下,UIView无法响应用户事件。
在init ButtonView之后使用此代码启用其userInteraction:
ButtionView.userInteractionEnabled = YES;
答案 2 :(得分:0)
没有改变任何重要的东西。但是想要在调用UITapGestureRecognizer方法之后调用你的Button动作方法。
ButtionView=[[UIView alloc]initWithFrame:CGRectMake(x, y, 84, 84)];
ButtionView.tag=i;
UIImageView *coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,ButtionView.frame.size.width,84)];
coverImageView.tag = i;
UIButton *notesbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
notesbutton.frame=CGRectMake(0, 0,40,40);
notesbutton.tag=i;
[notesbutton addTarget:self action:@selector(buttonClickedForNotes:) forControlEvents:UIControlEventTouchUpInside];
[ButtionView addSubview:coverImageView];
[ButtionView addSubview:notesbutton];
[notesbutton bringSubviewToFront:ButtionView];
[self.view addSubview:ButtionView];
//[ButtionView addGestureRecognizer:oneFingerSingleTap];
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(singleTap:)];
singleTapGestureRecognizer.numberOfTapsRequired = 1;
singleTapGestureRecognizer.enabled = YES;
singleTapGestureRecognizer.cancelsTouchesInView = NO;
[ButtionView addGestureRecognizer:singleTapGestureRecognizer];
[singleTapGestureRecognizer release];
}
- (void)singleTap:(UITapGestureRecognizer *)gesture{
NSLog(@"handle taps");
}
-(IBAction)buttonClickedForNotes:(id)sender{
NSLog(@"buttion action call");
}