0

UITableViewの行内にボタンがある場合にボタンのクリックを取得する方法は理解していますが、UITableViewCellサブクラスにボタンを追加し、UITableViewクラス内でボタンのクリックを取得する正しい方法がわかりません。すべてをlayoutSubviewsメソッドに入れるのを間違えていると思います。誰かが私を正しい方向に向けてくれませんか?

-(void) layoutSubviews 
{
//  UIButton *myButton1; <- This is declared as a property in my subclass header file

  [super layoutSubviews];

  //self.textLabel.frame = CGRectMake(0, 0, 40, 20);

  //        cell.textLabel.text = timeElapsed;
  self.textLabel.frame = CGRectMake( 5, 5, 80, self.frame.size.height - 10 );
  self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;   

  // Don't need UIButton alloc because method below does it for us..
  myButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];

  //CGRect cellFrame = [self.tableView rectForRowAtIndexPath:indexPath];
  CGRect cellFrame = self.frame;

  myButton1.tag = idButton;

  int nButtonWidth  = 80;
  int nButtonHeight = 30;
  int nActualCellWidth = cellFrame.size.width - 40;
  int nButtonDeltaX = ( nActualCellWidth      - nButtonWidth  ) / 2;
  int nButtonDeltaY = ( cellFrame.size.height - nButtonHeight ) / 2;
  myButton1.frame = CGRectMake( nButtonDeltaX, nButtonDeltaY, nButtonWidth, nButtonHeight );      

  [myButton1 setTitle:@"OK" forState:UIControlStateNormal];

  // PDS: Add delaget for stopwatch clicking..
//  [myButton1 addTarget:self action:@selector(buttonClickedStopWatch:) forControlEvents:UIControlEventTouchUpInside];  

  [self.contentView addSubview:myButton1];      
  [self.contentView bringSubviewToFront:myButton1];
}
4

1 に答える 1

4

まず、layoutSubviewsは複数回呼び出される可能性があるため、ボタンを作成してビュー階層に追加するのは実際には適切な場所ではありません。これにより、毎回新しいボタンが作成されます。指定した初期化子でボタンを作成し、フレームなどの設定にはlayoutSubviewsのみを使用する必要があります。

次に、UITableViewのインスタンスは、通常、ボタンのクリックを処理するのに適した場所ではありません。これは通常、UIViewControllerのサブクラスのタスクです。

タップアクションを処理するためにどのクラスを選択する場合でも、カスタムボタンのセルにプロパティを追加することから始めます。次に、UITableViewまたはUIViewControllerに、プロパティにアクセスしてターゲットをselfに設定することにより、そのコントロールイベントのアクションターゲットを追加さ​​せます。

于 2012-07-03T20:34:58.220 に答える