【问题标题】:Add Longpress gesture and Click event on UIButton在 UIButton 上添加 Longpress 手势和 Click 事件
【发布时间】:2012-07-22 10:12:34
【问题描述】:

我是 iPhone 新手。

我想在我的 Button 中同时添加长按手势和点击事件,这可能吗?

当我将这两个事件添加到按钮然后长按时,我的点击事件被触发(点击时我导航到新页面),但我的长按事件永远不会被触发。

这是我的代码 sn-p:

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];

如何添加这两个事件?

我们将不胜感激。

【问题讨论】:

标签: iphone ipad uibutton uigesturerecognizer long-press


【解决方案1】:

改行如下,

     [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]]; 最后一行出现错误,为什么?有语法错误吗?
  • 试试这个方法。 stringByAppendingPathComponent。您不需要自己添加“/”。
  • 是的,我需要自己附加/。我试过 stringByAppendingPathComponent 面临同样的问题。
猜你喜欢
  • 2012-01-05
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
  • 2013-12-01
  • 1970-01-01
相关资源
最近更新 更多