how can I set max length of UITextField in Alert?
What is the latest best practice for this in Swift 4?
This is my code example, but it will crash because UITextField doesn't exist at beginning.
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
let limitLength = 10
@IBOutlet weak var player1: UIButton!
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
@IBAction func player1Action(_ sender: UIButton) {
let alertController = UIAlertController(title: "Please enter you name", message: "Maximum 10 characters", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
// do something with textField
self.player1.setTitle("\(textField.text!)", for: .normal)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
textField.placeholder = "Name"
})
self.present(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textField.delegate = self
}
Many thanks for your time.