2012-03-27 7 views
1

設定ページを作成していて、最初のセクションの最初の行にUISwitchが必要です。ページのロードが、最初のセクションの最初の行は、UISwitchを持っており、他のすべては、「テスト」を言うときxCode 4.2 1つのセクションの1つの行にUISwitchを割り当てると、奇妙な動作が発生します... IOS

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 

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

    if (indexPath.section == 0){ 
     [[cell textLabel] setText:[table1labels objectAtIndex:indexPath.row]]; 
     if (indexPath.row == 0 && indexPath.section == 0){ 
      UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero]; 
      cell.accessoryView = switchview; 
     }else{ 
      [[cell detailTextLabel] setText:@"test"]; 
     } 
    }else{ 
     [[cell textLabel] setText:[table2labels objectAtIndex:indexPath.row]]; 
     [[cell detailTextLabel] setText:@"test"]; 
    } 

    return cell; 
} 

:私は、次のコードを使用して、これを達成しました。ただし、ページをスクロールすると、より多くのUISwitchがランダムに表示されます。テキスト "test"を置き換えるのではなく、左に押すだけです。それはすべての人に起こるわけではありません。セルがビューを離れてビューに戻ると、ランダムに表示されます。誰も私にこれを修正する方法を教えてもらえますか?

私は5.1シミュレータでのみテストしました。実際のデバイスではありません。これは単にシミュレータの問題かもしれませんか?

答えて

2

問題の重要な部分である非常に同じセルを再利用し続けます。

ここで、UISwitchに最初に使用されたセルが、表示したいインデックスと同じでないインデックスに再利用されたとします。その場合は、UISwitchを手動で非表示にするか置き換える必要があります。

代わりに、実際には似ていないセルに対して異なるセル識別子を使用することを強くお勧めします。

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *cellIdentifier; 
    if (indexPath.row == 0 && indexPath.section == 0) 
    { 
     cellIdentifier = @"CellWithSwitch"; 
    } 
    else 
    { 
     cellIdentifier = @"PlainCell"; 
    } 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; 
    } 

    if (indexPath.section == 0) 
    { 
     [[cell textLabel] setText:[table1labels objectAtIndex:indexPath.row]]; 
     if (indexPath.row == 0 && indexPath.section == 0) 
     { 
      UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero]; 
      cell.accessoryView = switchview; 
     } 
     else 
     { 
      [[cell detailTextLabel] setText:@"test"]; 
     } 
    }else{ 
     [[cell textLabel] setText:[table2labels objectAtIndex:indexPath.row]]; 
     [[cell detailTextLabel] setText:@"test"]; 
    } 

    return cell; 
} 
+0

それで、私は同じセルを使用しないように構造を完全に変更する必要があると言っていますか?私にこの例を教えてください。 – James

+0

これは実際には異なる唯一のセルです。しかし、私は自分のコードを更新しました。そのセルではないものについては、 'cell.accessoryView = nil;'と書いてあり、それはうまくいくようでした。これを行うより良い方法はありますか? – James

+0

私はより良い代替案を検討する方法について私の更新答えを見てください。 – Till

関連する問題