UIAlertController中のUITextFieldに文字が入っていない場合はボタンを押せないようにする
備忘録です
func alert(){
let ac = UIAlertController(title: "Test",
message: "テストです",
preferredStyle: .Alert)
let defaultAction:UIAlertAction = UIAlertAction(title: "Create",
style: UIAlertActionStyle.Default,
handler:{
(action:UIAlertAction!) -> Void in
if let textFields = ac.textFields as Array? {
for textField:UITextField in textFields {
println(textField.text)
}
}
NSNotificationCenter.defaultCenter().removeObserver(self)
})
defaultAction.enabled = false
let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.Cancel,
handler:{
(action:UIAlertAction!) -> Void in
})
ac.addAction(defaultAction)
ac.addAction(cancelAction)
ac.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
NSNotificationCenter.defaultCenter().addObserver(self, selector: "alertTextFieldDidChange:",
name: UITextFieldTextDidChangeNotification, object: nil)
presentViewController(ac, animated: true, completion: nil)
}
func alertTextFieldDidChange(notification:NSNotification) {
if let ac = self.presentedViewController as? UIAlertController {
var text: UITextField = ac.textFields?.first as UITextField
var create: UIAlertAction = ac.actions.first as UIAlertAction
create.enabled = countElements(text.text) > 0
}
}