简体   繁体   中英

Programmatically change state of a UISwitch bugs

I'm trying to dynamically change a UISwitch with the method [self.mySwitch setOn:YES animated:YES];

The state change as well in the code so that the mecanisme is working fine but in the view the state has not change. So I get a UISwitch shown as OFF and working as it was as ON.

When I tap on it, the switch became ON. So I have to tap it twice to launch the inCaseOff part of code.

I hope this is clear enough.

[EDIT]

This is the code you have asked

- (void)viewDidLoad
{
   [self manageTheSwitch];
}

- (void) manageTheSwitch{
    self.mySwitch = [[UISwitch alloc]init];
    if(randomObject != nil){
        [self.mySwitch setOn:YES animated:YES];
    }else{
        [self.mySwitch setOn:NO animated:YES];
    }
}

You're programmatically setting a different UISwitch to the one shown in your view. You shouldn't have to do [[UISwitch alloc]init] at all, instead you should retrieve it through an IBOutlet property in your controller (wired up to your view in IB).

Assuming you did wire up mySwitch, then all you need to do is remove this line:

self.mySwitch = [[UISwitch alloc]init];

Your problem is, that you're instantiating a new button in your manageTheSwitch method rather than accessing the one you created in the storyboard. Just eliminate that alloc init.

尝试使用UISwitch继承自UIControl的“ selected”属性: self.mySwitch.selected = YES;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM