2012-03-26 7 views
0

私はこれを長年検索してきましたが、明確な答えはありません。UISwitchスクロール時のリセットテーブルビュー

私はテーブルビューのセルにaccessoryViewとしてUISwitchを持っています。問題は、テーブルをスクロールするたびにスイッチが元の状態にリセットされることです。

はここに私のcellForRowAtIndexPath方法です:

-(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.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    switch1 = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease]; 
    [switch1 addTarget:self action:@selector(buttonPressed :) forControlEvents:UIControlEventValueChanged]; 
    [switch1 setOn:YES animated:NO]; 
    cell.accessoryView = switch1; 

    NSString *iconsImage = [[self iconsImages] objectAtIndex:[indexPath row]]; 
    UIImage *cellIcon = [UIImage imageNamed:iconsImage]; 
    [[cell imageView] setImage:cellIcon]; 

    CGRect labelFrame = CGRectMake(65, 18, 150, 25); 
    UILabel *iconsNameLabel = [[[UILabel alloc] initWithFrame:labelFrame] autorelease]; 
    iconsNameLabel.font = [UIFont boldSystemFontOfSize:18]; 
    iconsNameLabel.text = [iconsList objectAtIndex:indexPath.row]; 
    [cell.contentView addSubview:iconsNameLabel]; 

    return cell; 
} 

ところで、私は、ヘッダファイルに私のスイッチを宣言し、プロパティとして設定し、それを合成してきました。

+0

**スイッチが画面*をスクロールしてから再びオンにするたびにオンに戻り、オンに戻り、少しスクロールしても変更されることを意味しますか? – lnafziger

+0

スイッチが画面をスクロールすると、それが変わります... – GSethi

+0

これは私がコードに基づいて考えたものです。これは画面に表示されるたびに新しいスイッチになるためです。 – lnafziger

答えて

1

このように、書かれたコードは、画面上に移動するたびに新しいボタンをすべてのセルに追加します。あなたはiconsImagesiconsList(私はNSArrayのものと仮定します)とよく似た何かをする必要があります。

1があなたのヘッダファイルに新しいNSMutableArrayを追加して、適切にあなたのソースファイルでそれを初期化します。

は、ここであなたがする必要があるものです。これは2つの既存の配列とほぼ同じでなければなりません。これをiconsSwitchStatesとしましょう。あなたは既に(buttonPressed:)あなたは、スイッチの状態を設定する必要が持っている機能では

[switch1 setTag:indexPath.row]; 
if ([iconsSwitchStates count] > indexPath.row) { 
    [switch1 setOn:[iconsSwitchStates objectAtIndex:[indexPath.row]]; 
} 

3:あなたは、スイッチを作成するとき

2は、このようなタグや状態を設定します。

[iconsSwitchStates replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:sender.on]]; 
0

Inafzigerの答え、私は代替を使用しています(1 UISwitchのため、わずかに異なるアプローチ)に基づいて:あなたはあなたがしているあなたのcellforRowAtIndexPath:方法でNSMutableArray *swStateUISwitch *sw

を(持っている

作成スイッチ):

[sw setOn:[swState count]]; 

そして、あなたの送信者の方法で:

if ([swState count] > 0) 
{ 
    [swState removeObjectAtIndex:0]; 
} 
else 
{ 
    [swState addObject:@"foo"]; 
}