如何在Table View ViewDidLoad方法中调用自定义单元格中声明的UISwitch?

时间:2013-02-02 18:09:48

标签: iphone ios xcode tableview uiswitch

我有一个TableView,其中包含UILabelUISwitch的自定义单元格。 UISwitch在Custom Cell中声明。我想在TableView的ViewDidLoad中调用此开关。 我想使用NSUserDefaults来保存UISwitch的状态。要加载值,我必须在ViewDidLoad中编写代码。

@interface LabelSwitchCustomCell : UITableViewCell {
    IBOutlet UILabel  *mainLabel;
    IBOutlet UISwitch *switchButton;
}

@property (nonatomic, retain) IBOutlet UILabel  *mainLabel;
@property (nonatomic, retain) IBOutlet UISwitch *switchButton;

@end

2 个答案:

答案 0 :(得分:1)

您可以从代码中的任何位置在NSUserDefaults中保存UISwitch的状态。 您可以通过以下方式设置/加载开关状态:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
//Set switch states
    if (indexPath.row == 0) 
                cell.switchBtn.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Switch1State"];
            else if(indexPath.row == 1)
                cell.switchBtn.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Switch2State"];
            else if(indexPath.row == 2)
                cell.switchBtn.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Switch3State"];
// Set switch states

// Set action for your switch
[cell.switchBtn addTarget:self action:@selector(switchingBtn:) forControlEvents:UIControlEventValueChanged];
    }

答案 1 :(得分:1)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexpath
{
    LabelSwitchCustomCell *switchCell = (LabelSwitchCustomCell *)[tableView dequeueReusableCellWithIdentifier:@"YOUR_CELL_IDENTIFIER"];
    switchCell.switchButton.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"SwitchState"];
}

然后,在Interface Builder中,使用在自定义单元类中声明并实现的此操作连接交换机:

- (IBAction)switchFlipped:(id)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:self.switchButton.on forKey:@"SwitchState"];
}