iOS-如何以编程方式设置UISwitch


104

我想以编程方式将我的UISwitch设置为打开或关闭。我该怎么做?我是iOS新手。

Answers:


195

如果您使用的是UISwitch,那么正如在开发人员API中所见,该任务setOn: animated:就可以解决问题。

- (void)setOn:(BOOL)on animated:(BOOL)animated

因此,要在程序中将开关设置为ON,可以使用:

目标C

[switchName setOn:YES animated:YES];

迅速

switchName.setOn(true, animated: true)

25

UISwitches具有应设置的名为“ on”的属性。

您是在谈论iOS应用还是移动网站?


10

使用此代码解决iOS中的开关中的开/关状态问题

- (IBAction)btnSwitched:(id)sender {
    UISwitch *switchObject = (UISwitch *)sender;
    if(switchObject.isOn){
        self.lblShow.text=@"Switch State is Disabled";
    }else{
        self.lblShow.text=@"Switch State is Enabled";
    }                

为此专线投票:UISwitch *switchObject = (UISwitch *)sender;
不是用户的用户

2

我也setOn:animated:为此使用它,并且工作正常。这是我在应用程序中viewDidLoad用来切换输入UISwitch代码以加载预设的代码。

// Check the status of the autoPlaySetting
BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];

[self.autoplaySwitch setOn:autoPlayOn animated:NO];

0

ViewController.h

- (IBAction)switchAction:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *lbl;

ViewController.m

- (IBAction)switchAction:(id)sender {

    UISwitch *mySwitch = (UISwitch *)sender;

    if ([mySwitch isOn]) {
        self.lbl.backgroundColor = [UIColor redColor];
    } else {
        self.lbl.backgroundColor = [UIColor blueColor];   
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.