Skip to content

Instantly share code, notes, and snippets.

@TheCodedSelf
Last active March 31, 2024 18:00
Show Gist options
  • Save TheCodedSelf/c4f3984dd9fcc015b3ab2f9f60f8ad51 to your computer and use it in GitHub Desktop.
Save TheCodedSelf/c4f3984dd9fcc015b3ab2f9f60f8ad51 to your computer and use it in GitHub Desktop.
Disable Alert Controller button if Alert Controller text field is empty or whitespace
import UIKit
// Create an alert controller
let alertController = UIAlertController(title: "Alert", message: "Please enter text", preferredStyle: .alert)
// Create an OK Button
let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
// Print "OK Tapped" to the screen when the user taps OK
print("OK Tapped")
}
// Add the OK Button to the Alert Controller
alertController.addAction(okAction)
// Add a text field to the alert controller
alertController.addTextField { (textField) in
// Observe the UITextFieldTextDidChange notification to be notified in the below block when text is changed
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main, using:
{_ in
// Being in this block means that something fired the UITextFieldTextDidChange notification.
// Access the textField object from alertController.addTextField(configurationHandler:) above and get the character count of its non whitespace characters
let textCount = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).count ?? 0
let textIsNotEmpty = textCount > 0
// If the text contains non whitespace characters, enable the OK Button
okAction.isEnabled = textIsNotEmpty
})
}
@Sigvard84
Copy link

really cool, thanks.
I would add
okAction.isEnabled = false
before add it to alertController since the TextField appears empty the first time.

I second this. The OK button will start out as enabled if this is not done. Minor line of code but pretty essential given the purpose of the whole procedure.

@asaadreh-meister
Copy link

Pretty neat. I didn't want to create a new method in an already clustered viewcontroller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment