UITableViewCellにUIGestureRecognizerを仕込む
ダブルタップとか長押しとかを仕込むときに便利なのがGestureRecognizer。
最初はLabelとかに仕込もうとしたんだけど、何だかうまく行かず…。
UIImageViewでもダメだし…ということで、新しいUIViewを作ってそこに仕込むことにした。
仕込みとしては以下のような感じ。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UIView *tapZone; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { tapZone = [[UIView alloc] initWithFrame:CGRectMake(50, 0, 220, cell.frame.size.height)]; tapZone.tag = 20; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureTest:)]; [tapZone addGestureRecognizer:tap]; } else{ tapZone = (UIView *)[[cell.contentView viewWithTag:0] viewWithTag:20]; } }
扱いは普通のビューと同じような感じ。
そして、レコグナイザーで設定したメソッドに実行メソッドを書く、というかんじです。
- (void)gestureTest:(UIGestureRecognizer *)recognizer{ NSLog(@"gestureTest[%@]",recognizer); NSLog(@"[%@]",recognizer.view); UITableViewCell *cell = (UITableViewCell *)[[[recognizer view] superview] superview]; NSIndexPath *path = [tableView_ indexPathForCell:cell]; NSLog(@"Pushed :: [%d]",path.row); switch (recognizer.state) { case UIGestureRecognizerStateEnded: //ここにタップ時のアクションとか break; case UIGestureRecognizerStateCancelled: break; } }
インデックスパスは、ボタンの配置のようにすれば手に入れられます。
SwitchでStateを分けて、そこで実行アクションを指定します。
この部分はどのレコグナイザー を使うかで変わるので、NSLogでStateを確認するといい。ググれば一覧も出てくるはず。
コメントする