iOS: come impostare un interruttore UIS a livello di codice


104

Voglio impostare il mio UISwitch su on o off a livello di programmazione. Come potrei farlo? Sono un principiante di iOS.

Risposte:


195

Se stai usando un UISwitch, quindi come visto nell'API per sviluppatori, l'attività setOn: animated:dovrebbe fare il trucco.

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

Quindi, per impostare l'interruttore su ON nel tuo programma, dovresti usare:

Objective-C

[switchName setOn:YES animated:YES];

veloce

switchName.setOn(true, animated: true)

25

Gli switch UIS hanno una proprietà chiamata "on" che dovrebbe essere impostata.

Stai parlando di un'app iOS o di un sito web mobile?


10

Usa questo codice per risolvere il problema dello stato di accensione / spegnimento nello switch in 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";
    }                

Votato per questa riga:UISwitch *switchObject = (UISwitch *)sender;
Utente che non è un utente

2

Uso anche setOn:animated:per questo e funziona bene. Questo è il codice che uso in un'app viewDidLoadper attivare o disattivare un UISwitchcodice in modo che carichi il preset.

// 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];   
    }
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.