【问题标题】:change uiswitch based on state of another uiswitch根据另一个 uiswitch 的状态更改 uiswitch
【发布时间】:2014-03-26 23:18:45
【问题描述】:

我基本上有两个切换按钮,我希望用户从两个播放器或组播放中进行选择。但是,我不希望用户能够在用户单击另一个关闭时如此理想地选择这两个。如何最好地实施这一点?

  -(void)stateSwitchedtwoplayer:(id)sender {
        UISwitch *tswitch = (UISwitch *)sender;
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        [defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"twoplayerswitch"];


        [defaults synchronize];
    }

    -(void)stateSwitchedgroup:(id)sender {
        UISwitch *tswitch = (UISwitch *)sender;
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        [defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"groupswitch"];

        [defaults synchronize];
    }

【问题讨论】:

  • 仅供参考 - NSUserDefaults 具有 setBool:forKey: 方法。只需[defaults setBool:tswitch.on forKey:@"The Switch Key"];

标签: ios objective-c uiswitch


【解决方案1】:

你有这两个开关的参考资料吗? 如果是,它将是这样的:

-(void)stateSwitchedtwoplayer:(id)sender {
    UISwitch *tswitch = (UISwitch *)sender;
    self.switchGroup.on =! tswitch.isOn; //reference to group switch
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setBool: tswitch.isOn forKey:@"twoplayerswitch"];
    [defaults setBool: !tswitch.isOn forKey:@"groupswitch"];

    [defaults synchronize];
}

-(void)stateSwitchedgroup:(id)sender {
    UISwitch *tswitch = (UISwitch *)sender;
    self.switchTwoPlayer.on =! tswitch.isOn; //reference to two players switch
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setBool: tswitch.isOn forKey:@"groupswitch"];
    [defaults setBool: tswitch.isOn forKey:@"twoplayerswitch"];
    [defaults synchronize];
}

但如果您希望两个开关都可以关闭,那么您只需将其更改为打开

self.switchGroup.on =! tswitch.isOn == YES; //reference to group switch
self.switchTwoPlayer.on =! tswitch.isOn == YES; //reference to two players switch

【讨论】:

    【解决方案2】:

    您可以使用 KVO 来实现这一点。您可以在以下位置找到文档:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVOCompliance.html。但我建议你不要这样做。

    您应该为这些类型的操作实现一些UISegmentedControl。你为什么不看看:https://developer.apple.com/library/ios/documentation/uikit/reference/UISegmentedControl_Class/Reference/UISegmentedControl.html

    【讨论】:

      最近更新 更多