Как найти, когда ячейка tableView коснулась или зажала в iphone?

У меня есть заполненная таблица viewView. когда я нажал на ячейку tableView:didSelectRowAtIndexPath: запускается, но когда я написал touchesBegan:withEvent, чтобы найти события touch и Pinch для tableView, он не был запущен. Tableview выше представления состоит в том, что причина не запускается, если да, как найти, когда tableView или его определенная ячейка касается или сжимается.


Я нашел способ найти Pinch Or touch в ячейке табличного представления, сначала объявить объект UIPinchGestureRecognizer в tableView:didSelectRowAtIndexPath: т.е.

UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
[tblAccountsList addGestureRecognizer:pinch];
[pinch release];

затем напишите метод выбора ниже...

- (void)handlePinch:(UIGestureRecognizer *)recognizer {
    NSLog(@"Pinch");
}

когда я устанавливаю точку останова, она выполняется, но метод вызывался 3 раза. Если кто-нибудь найдет решение, поделитесь им, пожалуйста...

Заранее спасибо...

2 ответа

Решение

touchesBegan - это метод UIView и UITableViewCell, а не метод UIViewController & UITableViewController. так что вы можете создать пользовательский класс для UITableViewCell, который распознает событие touch и делегирует touch, он работает для меня.

  //TableViewCell.h

#import <UIKit/UIKit.h>

@class Util;

@interface TableViewCell : UITableViewCell {

}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;

@end
   //TableViewCell.m
#import "TableViewCell.h"
@implementation TableViewCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier      format:(NSString*)ec_format{

    if (self) {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

   }

   return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
//you receive touch here 
    NSLog(@"Category Touch %@",self.frame);


}

В табличном представлении вы можете добавить

- (void)viewDidLoad {

[super viewDidLoad];

// Add a pinch gesture recognizer to the table view.
UIPinchGestureRecognizer* pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
[self.tableView addGestureRecognizer:pinchRecognizer];

// Set up default values.
self.tableView.sectionHeaderHeight = HEADER_HEIGHT;
/*
 The section info array is thrown away in viewWillUnload, so it's OK to set the default values here. If you keep the section information etc. then set the default values in the designated initializer.
 */
rowHeight_ = DEFAULT_ROW_HEIGHT;
openSectionIndex_ = NSNotFound;
}


#pragma mark Handling pinches


-(void)handlePinch:(UIPinchGestureRecognizer*)pinchRecognizer {

/*
 There are different actions to take for the different states of the gesture recognizer.
 * In the Began state, use the pinch location to find the index path of the row with which the pinch is associated, and keep a reference to that in pinchedIndexPath. Then get the current height of that row, and store as the initial pinch height. Finally, update the scale for the pinched row.
 * In the Changed state, update the scale for the pinched row (identified by pinchedIndexPath).
 * In the Ended or Canceled state, set the pinchedIndexPath property to nil.
 */

if (pinchRecognizer.state == UIGestureRecognizerStateBegan) {

    CGPoint pinchLocation = [pinchRecognizer locationInView:self.tableView];
    NSIndexPath *newPinchedIndexPath = [self.tableView indexPathForRowAtPoint:pinchLocation];
    self.pinchedIndexPath = newPinchedIndexPath;

    SectionInfo *sectionInfo = [self.sectionInfoArray objectAtIndex:newPinchedIndexPath.section];
    self.initialPinchHeight = [[sectionInfo objectInRowHeightsAtIndex:newPinchedIndexPath.row] floatValue];
    // Alternatively, set initialPinchHeight = uniformRowHeight.

    [self updateForPinchScale:pinchRecognizer.scale atIndexPath:newPinchedIndexPath];
}
else {
    if (pinchRecognizer.state == UIGestureRecognizerStateChanged) {
        [self updateForPinchScale:pinchRecognizer.scale atIndexPath:self.pinchedIndexPath];
    }
    else if ((pinchRecognizer.state == UIGestureRecognizerStateCancelled) || (pinchRecognizer.state == UIGestureRecognizerStateEnded)) {
        self.pinchedIndexPath = nil;
    }
}
}


-(void)updateForPinchScale:(CGFloat)scale atIndexPath:(NSIndexPath*)indexPath {

if (indexPath && (indexPath.section != NSNotFound) && (indexPath.row != NSNotFound)) {

    CGFloat newHeight = round(MAX(self.initialPinchHeight * scale, DEFAULT_ROW_HEIGHT));

    SectionInfo *sectionInfo = [self.sectionInfoArray objectAtIndex:indexPath.section];
    [sectionInfo replaceObjectInRowHeightsAtIndex:indexPath.row withObject:[NSNumber numberWithFloat:newHeight]];
    // Alternatively, set uniformRowHeight = newHeight.

    /*
     Switch off animations during the row height resize, otherwise there is a lag before the user's action is seen.
     */
    BOOL animationsEnabled = [UIView areAnimationsEnabled];
    [UIView setAnimationsEnabled:NO];
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
    [UIView setAnimationsEnabled:animationsEnabled];
}
}

Он вызывается 3 раза, потому что вызывается каждый раз, когда меняется состояние распознавателя жестов, а не каждый раз, когда жест распознается:)

Попробуйте это изменение:

- (void)handlePinch:(UIGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateRecognized) {
        NSLog(@"Pinch");
    }
}

И проверить документы для распознаватели жестов здесь, в частности, state имущество.

Другие вопросы по тегам