在应用程序中,我创建了几个动态按钮并将其添加到UITableView,每个按钮都有一个触摸事件(UIControlEventTouchUpInside)和一个长按手势(UILongPressGestureRecognizer),我希望一次执行任何一个动作。所以如果用户触摸时只有按钮动作将被调用。如果用户长时间按下,则长按事件将被调用。如何处理UIButton上的触摸事件和手势事件?
目前,即使我长时间按下按钮,它总是会调用操作。
我应该怎么处理这个事件?有什么好的建议?
在应用程序中,我创建了几个动态按钮并将其添加到UITableView,每个按钮都有一个触摸事件(UIControlEventTouchUpInside)和一个长按手势(UILongPressGestureRecognizer),我希望一次执行任何一个动作。所以如果用户触摸时只有按钮动作将被调用。如果用户长时间按下,则长按事件将被调用。如何处理UIButton上的触摸事件和手势事件?
目前,即使我长时间按下按钮,它总是会调用操作。
我应该怎么处理这个事件?有什么好的建议?
为了不触发这两个你应该国旗的全局变量或标签上的按钮,所以在UIControlEventTouchUpInside
目标可以过滤作用。
因此,让我们假设您的UILongPressGestureRecognizer
在发生火灾时调用longPress
,并在您的自定义单元格中初始化。 & UIControlEventTouchUpInside
调用目标btnPressed
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.button addGestureRecognizer:longPress];
[self.button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
选择通话时,您的自定义单元格内:
-(void)longPress:(UIButton*)btn
{
// Flag the button,
self.button.tag = 1;
// Do LongPress stuff.
}
按钮的目标为UIControlEventTouchUpInside
- (void)btnPressed:(id)sender {
UIButton *senderButton = sender;
if(senderButton.tag == 1) {
// Long press has been executed, set back the flag to 0
senderButton.tag = 0;
} else {
// Long press not executed
// Do the TouchUpInside stuff.
}
}
在泰伯维的cellForRowAtIndex使用此代码:
[cell.btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
而且cellForRowAtIndex之外实现此方法。
-(void)btnPressed:(UIButton*)btn
{
//Do whatever
}
而对于长按使用此代码
`UILongPressGestureRecognizer` *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[cell.button addGestureRecognizer:longPress];
长按的方法是
-(void)longPress:(UIButton*)btn
{
//Do whatever
}
您可以在按钮的动作事件中添加以下代码。我已经完成了tableview中多个复选框的代码。借助此代码,您可以获得TableView记录的IndexPath。我希望这对你有用。
- (IBAction)btnPressed:(UIButton *)sender {
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.tblView];
NSIndexPath *indexpath = [self.tblView indexPathForRowAtPoint:touchPoint];
NSLog(@"%ld",(long)indexpath.row);
}
重复:http://stackoverflow.com/questions/30859203/uibutton-with-single-press-and-long-press-events-swift – Frankie
可能重复[与长按和Touchup里面的UIbutton](http://stackoverflow.com/questions/6660282/uibutton-with-longpress-and-touchup-inside) –