I am creating an registration dialog in swift with 3 text field and one Switch and I successfully add three text field two the Alert. The following code shows the same.
let alertController = UIAlertController(title: "Register", message: "", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
exit(0)
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Sign UP", style: .Default) { (action) in
// ...
let name0 = alertController.textFields![0] as UITextField
print("Text field: \(name0.text)")
let email1 = alertController.textFields![1] as UITextField
print("Text field: \(email1.text)")
let company2 = alertController.textFields![2] as UITextField
print("Text field: \(company2.text)")
}
alertController.addAction(OKAction)
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Name"
textField.keyboardType = .EmailAddress
}
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Email"
textField.secureTextEntry = false
}
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Company"
textField.secureTextEntry = false
}
self.presentViewController(alertController, animated: true) {
// ...
}
Now I need to add a switch programmatically to the Alert View.We are doing this in Swift2. Is it possible?, i am new to Swift.
This may help you.
Add this method call alertController.view.addSubview(createSwitch())
in above code after alertController.addAction(OKAction)
.
func createSwitch () -> UISwitch{
let switchControl = UISwitch(frame:CGRectMake(10, 20, 0, 0));
switchControl.on = true
switchControl.setOn(true, animated: false);
switchControl.addTarget(self, action: "switchValueDidChange:", forControlEvents: .ValueChanged);
return switchControl
}
func switchValueDidChange(sender:UISwitch!){
print("Switch Value : \(sender.on))")
}
OutPut :