2011-05-25 110 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代替。