まゆたまガジェット開発逆引き辞典

電子工作やプログラミングのHowtoを逆引き形式で掲載しています。作りたいモノを決めて学んでいくスタイル。プログラマではないので、コードの汚さはお許しを。参照していないものに関しては、コピペ改変まったく問いません

カスタムセルにボタンを追加して処理を行う

例えばセルに表示させたツイートにFavボタンをつけたいなど、カスタムセルにボタンを追加したい場合の処理です。
カスタムセルの作り方はこれをベースにして、追加させるところのみ書きました。

まず、ボタンを設置してTagを設定します。ここでは7にしてあります。ラベルや画像同様、ひも付けはしません。

・ViewController.h

@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate> {
...
UIButton *FavBtn;

...
@property (nonatomic, retain) UIButton *FavBtn;
}

・ViewController.m

...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
 FavBtn = (UIButton*)[cell viewWithTag:7];
   
  [FavBtn addTarget:self action:@selector(cellTouchInfo:event:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

-(void)cellTouchInfo:(id)inSender event:(UIEvent*)event{
    // タップされた位置を検出
    UITouch *celltouch = [[event allTouches] anyObject];
    CGPoint p = [celltouch locationInView:_tweetTable];
    NSIndexPath *indexPath = [_tweetTable indexPathForRowAtPoint:p];
    int cellno = indexPath.row;
    NSLog( @"%d",cellno );
    
//タップされてからの処理を書く
 ...
}