2012-02-14 5 views
1

UITableViewの1つの行にUIButtonを追加したいのですが、私は非常に混乱しています。UITableViewの1行にUIButtonを追加する

私は次のコードを使用すると、最初は2行目のボタンが表示されますが、上下にスクロールすると(テーブルに50行あります)、ほぼすべての行に。 私が間違って何をやっている中ボタン:(

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 

cell.textLabel.text = [NSString stringWithFormat:@"Cell #%i", indexPath.row + 1]; 

if (indexPath.row == 2) 
{ 
    //Create the button and add it to the cell 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [button addTarget:self 
       action:@selector(customActionPressed:) 
    forControlEvents:UIControlEventTouchDown]; 
    [button setTitle:@"Custom Action" forState:UIControlStateNormal]; 
    button.frame = CGRectMake(150.0f, 5.0f, 150.0f, 30.0f); 
    [cell addSubview:button]; 
} 
return cell; 
} 

事前に多くの感謝を!

答えて

0

あなたがスクロールすると、ボタンを削除する必要があるので、彼らが画面の外に行くように、細胞が再利用されている。

私がやることはあなたのceにボタンを追加することですxlibでllし、あなたが望む行を除くすべてのセルで非表示に設定します。

cellForRowAtIndexPathでは、ボタンをコードの先頭に非表示にしてから、目的の行に表示するように設定します。 このように行を再利用すると、ボタンは非表示に設定されます

1

これは、セルに2つの異なる識別子を使用して実装できます。

このような何か:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 
    static NSString *ButtonCellIdentifier = @"ButtonCell"; 

    UITableViewCell *cell = nil; 
    if (indexPath.row == 2) { 
     cell = [tableView dequeueReusableCellWithIdentifier:ButtonCellIdentifier]; 
     if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ButtonCellIdentifier] autorelease]; 
      UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
      [button addTarget:self 
         action:@selector(customActionPressed:) 
      forControlEvents:UIControlEventTouchDown]; 
      [button setTitle:@"Custom Action" forState:UIControlStateNormal]; 
      button.frame = CGRectMake(150.0f, 5.0f, 150.0f, 30.0f); 
      [cell.contentView addSubview:button]; 
      // in case you need the button later 
      button.tag = 1024; 
     } 
     // in case you have to configure the button; 
     UIButton *button = (UIButton *)[cell.contentView viewWithTag:1024]; 
     // configure button 
    } 
    else { 
     cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
     } 
    } 
    cell.textLabel.text = [NSString stringWithFormat:@"Cell #%i", indexPath.row + 1]; 
    return cell; 
} 
+0

HIマティアス。それはボタンを作成しません...この例では間違いはありますか? – user930731

関連する問題