Posted at

Swift2でUIAlertControllerに追加したUITextFieldにバリデーションを実施する

More than 3 years have passed since last update.


  • UIAlertController

let dialog: UIAlertController = UIAlertController(title: "ユーザ名登録", message: "名前を入力してください", preferredStyle:  UIAlertControllerStyle.Alert)


  • AlertAction

let signUpAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ (action: UIAlertAction!) -> Void in

print(dialog.textFields![0].text)
// any code
})
signUpAction.enabled = false


  • UITextField for UserName

dialog.addTextFieldWithConfigurationHandler { (textFieldUser: UITextField!) in

textFieldUser.placeholder = "1〜6文字"
textFieldUser.keyboardType = .Default
}


  • Validation

let textFieldValidationObserver: (NSNotification!) -> Void = { _ in

let min = 1
let max = 6
let userName = dialog.textFields![0].text
signUpAction.enabled = userName?.characters.count >= min && userName?.characters.count <= max
}


  • Notifications for textField changes

NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: dialog.textFields![0], queue: NSOperationQueue.mainQueue(), usingBlock: textFieldValidationObserver)

dialog.addAction(signUpAction)
self.presentViewController(dialog, animated: true, completion: nil)