Swift UISwitch不能正常工作
问题描述:
我在我的视图控制器上有一个UISwitch,我拥有它,所以当我切换它时,按钮的文本会发生变化。我第一次关闭它,并且它不起作用,但是如果你第二次尝试它,它会有效......我的代码中缺少一些东西吗?Swift UISwitch不能正常工作
UISwitchOutlet.addTarget(self, action: #selector(MainPageViewController.switchChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
func switchChanged(mySwitch: UISwitch) {
let value = UISwitchOutlet.on
if value {
self.enterRoom.titleLabel?.text = "Enter Room"
} else {
self.enterRoom.titleLabel?.textAlignment = NSTextAlignment.Center
self.enterRoom.titleLabel?.text = "Create"
}
}
答
请尝试以下。您的价值将始终开启,因为您正在设置开关打开状态。
func switchChanged(mySwitch: UISwitch) {
if mySwitch.isOn {
self.enterRoom.titleLabel?.text = "Enter Room"
} else {
self.enterRoom.titleLabel?.textAlignment = NSTextAlignment.Center
self.enterRoom.titleLabel?.text = "Create"
}
}
在if value {'conditional无效之前定义'let value = UISwitchOutlet.on'。它永远不会去其他选项。删除第一行并将第二行更改为'if mySwitch.on {' –
哦,我的错误,我认为我必须先设置默认值 – RubberDucky4444
只需添加到viewDidLoad'UISwitchOutlet.on = true' –