我的 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?
你必须打电话给super。所有 IBOutlet 都是隐式解包的可选。它们是
nil
,直到调用 awakeFronNib
。如果您在此之前尝试访问其中之一,则会出现异常。 override func viewDidLoad() {
super.viewDidLoad()
if switch1.on {
print("Switch is on")
}
else {
print("Switch is off"
}
}
可能是您的 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")
}
检查开关ON/OFF
if switchTapped.isOn == true {
switchTapped.isOn = true
}else {
switchTapped.isOn = false
}