2016-05-17 40 views
0

我在我的視圖控制器上有一個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" 


    } 
} 
+0

在if value {'conditional無效之前定義'let value = UISwitchOutlet.on'。它永遠不會去其他選項。刪除第一行並將第二行更改爲'if mySwitch.on {' –

+0

哦,我的錯誤,我認爲我必須先設置默認值 – RubberDucky4444

+0

只需添加到viewDidLoad'UISwitchOutlet.on = true' –

回答

1

請嘗試以下。您的價值將始終開啓,因爲您正在設置開關打開狀態。

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" 
    } 
}