3

我是 iPhone 新手。

我想向我的 Button 添加长按手势和单击事件,这可能吗?

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

这是我的代码片段:

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

如何添加这两个事件?

任何帮助将不胜感激。

4

1 回答 1

8

如下更改该行,

     [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

如果您使用 touchdown 事件,您的 click 事件将在您触摸按钮后立即触发。TouchupInside 触发 touchup 动作。

要获得标题,

 - (void)longPressDetected:(UIGestureRecognizer *)gestureRecognizer
{
    UIButton *button = (UIButton *)[gestureRecognizer view];
    NSLog(@"%@",[button titleForState:UIControlStateNormal]);
}
于 2012-07-24T06:08:28.843 回答