I think it’s pointless make the button for sending data available if data is empty. This is also meaningless for the user. All he’ll get is also empty data.

In some situations, the application may crashes. Same as mine.

Below is a solution to this problem for Swift 4.x-5.0 which I use in my application.

Add UITextFieldDelegate here:

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var yourTextField: UITextField!
@IBOutlet weak var yourButton: UIButton!

Add code below to your viewDidLoad:

yourTextField.delegate = self
yourButton.isEnabled = false
yourButton.alpha = 0.5

And finally implement it:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (yourTextField.text! as NSString).replacingCharacters(in: range, with: string)
if text.isEmpty {
 yourButton.isEnabled = false
 yourButton.alpha = 0.5
} else {
 yourButton.isEnabled = true
 yourButton.alpha = 1.0
}
 return true
}
Categories: App development