2016-10-22 24 views
-1

我的代碼不工作。我不知道爲什麼。問題是switchChanged函數的屬性。如果屬性爲空,則代碼正在工作。如何正確使用UISwitch?

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    let rect = CGRectMake(130, 100, 0, 0) 
    let uiSwitch = UISwitch(frame: rect) 
    uiSwitch.setOn(true, animated: true) 
    uiSwitch.addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged) 

    self.view.addSubview(uiSwitch) 
} 

func switchChanged(uiSwitch: UISwitch) { 
    var message = "Turn on the switch" 
    if uiSwitch.on { 
     message = "Turn off the switch" 
    } else { 
     message = "Turn on the switch" 
    } 
    let alert = UIAlertController(title: "Information", message: message, preferredStyle: UIAlertControllerStyle.Alert) 
    let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) 
    alert.addAction(action) 
    self.presentViewController(alert, animated: true, completion: nil) 
} 

錯誤:「的libC++ abi.dylib:與類型NSException的未捕獲的異常終止」

+0

您已經在標籤中指出了您對Swift的使用,因此無需將其添加到標題中。 –

回答

3

"switchChanged"是不是正確的選擇名字,你應該使用"switchChanged:"佔該參數。 switchChanged將是一個沒有參數的方法。

另外,在Swift中,您應該使用#selector(switchChanged(_:))來代替。這將在編譯過程中驗證選擇器的存在。

+0

uiSwitch.addTarget(self,action:#selector(ViewController.switchChanged(_ :)),forControlEvents:UIControlEvents.ValueChanged) –

+0

Xcode要求我在「#」之前插入「,」。 –

+0

但「switchChanged:」正在工作!謝謝! –