快速检查 viewDidLoad 上的 uiswitch 状态

问题描述 投票:0回答:3

我的 uiswitch 有问题。我需要知道应用程序第一次运行时 uiswitch 是打开还是关闭。 我尝试使用这段代码:

     @IBOutlet  weak var switch1: UISwitch!


      override func viewDidLoad() {
      super.viewDidLoad()
     if switch1.on {
        print("Switch is on")

    }
    else {


       print("Switch is off")
                }
    }

但是每次我收到此错误时:

  fatal error: unexpectedly found nil while unwrapping an Optional value

如何在不出现该错误的情况下打开 uiswitch?

ios swift uiswitch viewdidload unwrap
3个回答
2
投票

你必须打电话给super。所有 IBOutlet 都是隐式解包的可选。它们是

nil
,直到调用
awakeFronNib
。如果您在此之前尝试访问其中之一,则会出现异常。
还要验证开关的插座是否已连接。

 override func viewDidLoad() {
  super.viewDidLoad()
     if switch1.on {
        print("Switch is on")
    }
    else {
         print("Switch is off"
          }
    }

1
投票

可能是您的 switch1 未连接到故事板或 xib 中的 UISwitch。

if let switch = switch1 {
  if switch.on {
     print("switch is on")
  } else {
     print("switch is off")
  }
} else {
   println("Where's the switch")   
}

0
投票

检查开关ON/OFF

if switchTapped.isOn == true {
        switchTapped.isOn = true
    }else {
        switchTapped.isOn = false
    }
© www.soinside.com 2019 - 2024. All rights reserved.