简体   繁体   English

以编程方式更改UISwitch错误的状态

[英]Programmatically change state of a UISwitch bugs

I'm trying to dynamically change a UISwitch with the method [self.mySwitch setOn:YES animated:YES]; 我试图动态地改变与所述方法的UISwitch [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. 状态的变化,以及在代码中,使得mecanisme工作正常,但在视图状态已经无法改变。 So I get a UISwitch shown as OFF and working as it was as ON. 因此,我将UISwitch显示为OFF并按原样工作。

When I tap on it, the switch became ON. 当我在敲打,开关成了。 So I have to tap it twice to launch the inCaseOff part of code. 因此,我必须点按两次以启动代码的inCaseOff部分。

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. 您正在以编程方式将另一UISwitch设置为视图中显示的UISwitch。 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). 您完全不需要执行[[UISwitch alloc]init] ,而是应该通过控制器中的IBOutlet属性(连接到IB中的视图)来检索它。

Assuming you did wire up mySwitch, then all you need to do is remove this line: 假设您确实连接了mySwitch,那么您需要做的就是删除此行:

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. 您的问题是,您要在manageTheSwitch方法中实例化一个新按钮,而不是访问在情节提要中创建的按钮。 Just eliminate that alloc init. 只需消除该alloc init。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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