2011-05-25 23 views
0

我有一个带有自定义单元格的UITableview。其中一个customcell在其中有一个UISWITCH。当滚动表格视图时,即使设置为ON,开关的状态也会被重置。如何在滚动过程中保持开关的状态。任何帮助表示赞赏。UITableView中的UISwitch在滚动时重置为原始值

-(IBAction)sameDriver:(id)sender{ 

if ([sender isOn]){ 

    NSLog(@"%@",(otherdriver.drive ? @"YES" : @"NO")); 

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; 
    [defaults setBool: YES forKey: K_SWITCH_KEY]; 
    [defaults synchronize]; 

    Switchon = [defaults boolForKey: K_SWITCH_KEY]; 


if(Switchon){ 

    otherdriver.dfname.text = fname; 
    otherdriver.dlname.text = lname; 
    otherdriver.demail.text = email; 
    otherdriver.dpnum.text = phone; 

    } 
} 
else if(![sender isOn]){ 

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; 
    [defaults setBool: NO forKey: K_SWITCH_KEY]; 
    [defaults synchronize]; 

    NSLog(@"%@",(otherdriver.drive ? @"YES" : @"NO")); 

    Switchon = [defaults boolForKey: K_SWITCH_KEY]; 

    otherdriver.dfname.text = drfname; 
    otherdriver.dlname.text = drlname; 
    otherdriver.demail.text = dremail; 
    otherdriver.dpnum.text = drphone; 


}} 

我正在设置IB中的UISwitch。它在一个自定义的UITableviewcell中。

感谢

+0

如果您为自定义的UITableViewCell类发布代码,它会帮助 – NSExplorer 2011-05-25 18:11:04

+0

请在编辑中查看我的代码。 – 2011-05-25 20:41:21

+0

那么每个单元有一个开关? – 2011-05-25 21:08:59

回答

1

我假设你说,如果你向下滚动(开关单元获取滚动关闭屏幕),然后滚动备份(开关单元获取滚动回在屏幕上),则开关状态不被保留。它是否正确?

如果是这样,我猜想问题是该单元正在回收和重新创建。当你从dequeReusableCellWithIdentifier:CellIdentifier获得你的手机时,会发生这种情况。要解决这个问题,你需要给你的特殊单元格CellIdentifier

如果这仍不清楚,请粘贴您的代码tableView:cellForRowAtIndexPath:,我会尽力帮助您。

+0

func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - > UITableViewCell {cellId = tableView.dequeueReusableCell(withIdentifier:“TrackerFilterCell”)as! TrackerTypeFilterCellVC 如果allChecked ==真{ cell.switchButton.isOn =真 }其他{ 如果lastIndex的== 0 { cell.switchButton.isOn =假 } 否则,如果rowData.id ==“-1 “{ cell.switchButton.isOn = false } } return cell } – 2017-05-03 11:29:41

3

在头文件中,声明一个NSString来保存开关的状态。 让我们来命名它theSwitchPosition

然后,在其运行时的开关被触发你的方法,使theSwitchPosition按住开关的状态:

theSwitchPosition = [NSString stringWithFormat:@"%@", switchControl.on ? @"ON" : @"OFF"]; 

之后,在创建UISwitch的方法,设置开关的状态依据在包含数据的字符串上:

if ([theSwitchPosition isEqualToString:@"ON"]) { 
    mySwitch.on = YES; 
} else { 
    mySwitch.on = NO; 
} 

如果您的表视图中只有一个UISwitch,这将起作用。如果你有多个,你需要使用NSMutableArray代替。