1

我已经阅读了有关 UISwitches 的所有内容,但在我的情况下似乎无法弄清楚它们。我有 2 个 UISwitches。为了让我的代码正常工作,只有其中一个可以打开。我将如何做到这一点?

到目前为止,我已经尝试...

我的类.h

-(IBAction)sufSwitchChanged:(id)sender;

我的班级.m

-(IBAction)preSwitchChanged:(id)sender {
UISwitch *whichSwitch = (UISwitch *)sender;
BOOL setting = whichSwitch.isOn;
[newsPre setOn:setting animated:YES];
[techPre setOn:setting animated:YES];
}

....这有效,但它使两个开关都打开或关闭。我只需要弄清楚如何防止它们同时开启。

4

2 回答 2

3

注册两个 UISwitch 以观察针对另一个开关的UIControlEventValueChanged通知。就像是:

- (void)viewDidLoad { // or whatever method is appropriate
    UISwitch *a = <# initialize a #>;
    UISwitch *b = <# initialize b #>;

    [a addTarget:self action:@selector(toggleB:)   
         forControlEvents:UIControlEventValueChanged]; 

    [b addTarget:self action:@selector(toggleA:)   
         forControlEvents:UIControlEventValueChanged]; 
}

- (IBAction)toggleA:(id)sender {
    [b setOn:NO animated:YES];
}

- (IBAction)toggleB:(id)sender {
    [a setOn:NO animated:YES];
}

您也可以在 Interface Builder 中设置这种关系。

于 2011-04-11T03:19:51.637 回答
0

请注意您如何在此处将两个开关设置为相同的值:

[newsPre setOn:setting animated:YES];
[techPre setOn:setting animated:YES];

您要检查哪一个是发件人,然后将另一个设置为setting. 为此,您需要在每个开关上设置一个标签,或者可能对其进行子类化。有关检测哪个开关是哪个开关的更多信息,请参阅这篇文章,其中包含一些很好的信息。

于 2011-04-11T03:05:00.947 回答