根据另一个uiswitch的状态改变uiswitch

时间:2014-03-26 23:18:45

标签: ios objective-c uiswitch

我基本上有两个切换按钮,我希望用户从两个玩家或小组游戏中进行选择。但是,我不希望用户能够选择这两个,所以当用户点击一个时,另一个关闭。如何最好地实现这个?

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

2 个答案:

答案 0 :(得分:3)

您是否有两台交换机的参考? 如果是,它将是这样的:

-(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

答案 1 :(得分:0)

您可以使用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