【问题标题】:iOS - How to set a UISwitch programmaticallyiOS - 如何以编程方式设置 UISwitch
【发布时间】:2011-12-09 15:06:24
【问题描述】:

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

【问题讨论】:

    标签: objective-c ios


    【解决方案1】:

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

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

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

    Objective-C

    [switchName setOn:YES animated:YES];
    

    斯威夫特

    switchName.setOn(true, animated: true)
    

    【讨论】:

      【解决方案2】:

      UISwitch 有一个应该设置的名为“on”的属性。

      您指的是 iOS 应用还是移动网站?

      【讨论】:

        【解决方案3】:

        使用此代码解决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;
        【解决方案4】:

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

        // Check the status of the autoPlaySetting
        BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];
        
        [self.autoplaySwitch setOn:autoPlayOn animated:NO];
        

        【讨论】:

          【解决方案5】:

          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];   
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-10-01
            • 2011-12-19
            • 2011-01-02
            • 1970-01-01
            • 1970-01-01
            • 2014-01-26
            • 2012-04-19
            相关资源
            最近更新 更多