3

I am new to iPhone.

I want to add both a long press gesture and a click event to my Button, is this possible?

When I add both events to the button and then long press, my click event gets fired (on click I navigate to a new page), but my long press event never gets fired.

Here is my code snippet:

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

How do I add both events?

Any help will be appreciated.

Andy
  • 723
  • 9
  • 24
Krunal
  • 6,440
  • 21
  • 91
  • 155

1 Answers1

8

Change the line as follows,

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

You click event will be fired as soon you touch the button if you use touchdown event. TouchupInside fires the action on touchup.

To get title ,

 - (void)longPressDetected:(UIGestureRecognizer *)gestureRecognizer
{
    UIButton *button = (UIButton *)[gestureRecognizer view];
    NSLog(@"%@",[button titleForState:UIControlStateNormal]);
}
Vignesh
  • 10,205
  • 2
  • 35
  • 73
  • Thanx this is working, How to Get Button Text of Longpressed button ? – Krunal Jul 24 '12 at 06:13
  • `NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; [[NSFileManager defaultManager] removeItemAtPath:documentsDirectory error: NULL]; documentsDirectory=[documentsDirectory stringByAppendingString:@"/%@",[btn titleForState:UIControlStateNormal]];` I am getting error at last line why ? is there any syntax mistake ? – Krunal Jul 24 '12 at 06:30
  • try this method instead. stringByAppendingPathComponent. you do not need to add the '/' yourself. – Vignesh Jul 24 '12 at 06:32
  • yes i need to append `/` by my self. i tried with `stringByAppendingPathComponent` facing same problem. – Krunal Jul 24 '12 at 06:36