Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'NSNotification.Name' has no member 'UITextField'

With Swift 4.2, getting following error, that was working fine with Swift 4.

Type 'NSNotification.Name' has no member 'UITextField'

Here is my error code.

NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
            loginAction.isEnabled = textField.text != ""
        }

Full Code:

@IBAction func alertWithLogin(){

    let alertController = UIAlertController(title: "Please Enter Credential", message: nil, preferredStyle: .alert)

    // ADD ACTIONS HANDLER
    let loginAction = UIAlertAction(title: "Login", style: .default) { (_) in

        let loginTextField = alertController.textFields![0] as UITextField
        let passwordTextField = alertController.textFields![1] as UITextField

        // do something with after login
    }
    loginAction.isEnabled = false
    alertController.addAction(loginAction)

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
        // do something
    }
    alertController.addAction(cancelAction)

    // ADD TEXT FIELDS
    alertController.addTextField { (textField) in
        textField.placeholder = "Email"
    }
    alertController.addTextField { (textField) in
        textField.placeholder = "Password"
        textField.isSecureTextEntry = true

        // enable login button when password is entered
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
            loginAction.isEnabled = textField.text != ""
        }
    }

    // PRESENT
    present(alertController, animated: true)
}

enter image description here

like image 636
Krunal Avatar asked Sep 14 '18 04:09

Krunal


2 Answers

textDidChangeNotification is a member of UITextField (and UITextView).

NotificationCenter.default.addObserver(
    self,
    selector: #selector(self.keyboardDidShow(notification:)),
    name: UITextField.textDidChangeNotification,
    object: nil)
like image 121
rmaddy Avatar answered Nov 20 '22 01:11

rmaddy


I faced the same problem,

Here is the simplest solution:

Instead of using forName: NSNotification.Name.UITextField.textDidChangeNotification

Use like this in forName: Parameter:

NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
//Your code goes here...
        }
like image 6
iHarshil Avatar answered Nov 20 '22 02:11

iHarshil