在UIButton上添加长按手势和单击事件

3

我刚开始接触iPhone。

我想在我的按钮上同时添加长按手势和点击事件,这可行吗?

当我将两个事件都添加到按钮上,然后长按按钮时,点击事件会被触发(点击后我会导航到新页面),但是我的长按事件却无法触发。

以下是我的代码片段:

button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(xpos, ypos, 120,130);
[button setBackgroundImage:[UIImage imageNamed:@"ibook2.png"] forState:UIControlStateNormal];
[button setTitle:[NSString stringWithFormat:@"32"]];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];

LongPress = [[UILongPressGestureRecognizer alloc] init];
[LongPress addTarget:self action:@selector(longPressDetected:)];
LongPress.delegate = (id<UIGestureRecognizerDelegate>)self;
[button addGestureRecognizer:LongPress];
[LongPress release];

[self.view addSubview:button];

我该如何添加这两个事件呢? 任何帮助都将不胜感激。

1
可能是重复的 https://dev59.com/LG445IYBdhLWcg3wgqnT?rq=1 - Paresh Navadiya
1个回答

8
将这行代码修改为以下内容:
     [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

如果您使用touchdown事件,当您点击按钮时,单击事件将立即触发。TouchupInside在touchup时触发操作。

要获取标题,

 - (void)longPressDetected:(UIGestureRecognizer *)gestureRecognizer
{
    UIButton *button = (UIButton *)[gestureRecognizer view];
    NSLog(@"%@",[button titleForState:UIControlStateNormal]);
}

谢谢,这个可行。如何获取长按按钮的文本? - Krunal
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; [[NSFileManager defaultManager] removeItemAtPath:documentsDirectory error: NULL]; documentsDirectory=[documentsDirectory stringByAppendingString:@"/%@",[btn titleForState:UIControlStateNormal]]; 我在最后一行遇到了错误,为什么?有语法错误吗? - Krunal
尝试使用这个方法:stringByAppendingPathComponent。你不需要手动添加“/”。 - Vignesh
是的,我需要自己附加“/”。我尝试使用“stringByAppendingPathComponent”遇到了同样的问题。 - Krunal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接