【问题标题】:How to call UISwitch declared in Custom Cell in Table View ViewDidLoad method ?如何在表格视图 ViewDidLoad 方法中调用自定义单元格中声明的 UISwitch?
【发布时间】:2013-01-17 20:41:05
【问题描述】:

我有一个 TableView 和一个自定义单元格,该单元格有 UILabelUISwitch。 UISwitch 在自定义单元格中声明。我想在 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

【问题讨论】:

    标签: iphone ios xcode tableview uiswitch


    【解决方案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"];
    }
    

    【讨论】:

    • 谢谢。但开关状态始终保持为真。即使在模拟器上,如果我关闭开关,它也会再次变为 True 状态 -
    【解决方案2】:

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

        - (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];
        }
    

    【讨论】:

    • 谢谢。但开关状态始终保持为真。即使在模拟器上,如果我关闭开关,它也会再次变为 True 状态
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多