在xcode中使用UISwitch的If/Then语句



我试图让我的应用程序运行一个数学公式时,UISwitch被设置为"On"的位置,另一个当它被设置为"off"的位置。

我试着像这样把它摆出来:

if switch = on, then [first formula]

如果switch = off,则[第二个公式]

我该怎么写呢?

=============
编辑:

这是我目前试图编码它的方式。

-(IBAction)switchValueChanged:(UISwitch *)sender
{
if(sender.on)
{
-(float)conver2inches: (NSString *)mmeters {
return [mmeters floatValue]/25.4f;
}
-(IBAction)calculate:(id)sender{
float answer = [self conver2inches:entry.text];
 output.text=[NSString stringWithFormat:@"%f",answer];}}
else{
-(float)conver2mmeters:(NSString *)inches {
    return [inches floatValue]*25.4f;
}
-(IBAction)calculate:(id)sender{
    float answer = [self conver2mmeters:entry.text];
    output.text=[NSString stringWithFormat:@"%f",answer];
}}
}

给定:

@property (nonatomic) IBOutlet UISwitch *switch;

:

self.switch.on ? [self formula1] : [self formula2];

您需要将这样的函数连接到uiswitch的值更改事件。

-(IBAction) switchValueChanged:(UISwitch *) sender
{
    if(sender.on)
    {
    ...
    }
    else
    {
    ...
    }
}

下面是一个在语句中使用uiswich on或off的例子:

-(IBAction)onOffSwitch:(id)sender{
if(onOffSwitch.on) {
    // lights on
    [onOffLabel setText:@"Lights Currently On"];
    onOffLabel.textColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor colorWithRed:255.0/255.0 green:219.0/255.0 blue:52.0/255.0 alpha:1.0];
}
else {
    // lights off
    self.view.backgroundColor = [UIColor blackColor];
    [onOffLabel setText:@"Lights Currently Off"];
    onOffLabel.textColor = [UIColor whiteColor];
}
}

UISwitch有一个名为的属性,您可以使用它来检测开关是打开还是关闭。或者你是在问,当开关实际上被翻转时,如何编写代码来执行 ?

最新更新