LoginSignup
6
6

More than 5 years have passed since last update.

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

Posted at
  • 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)
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6