20

使用 Swift 4.2,出现以下错误,这在 Swift 4 中运行良好。

类型“NSNotification.Name”没有成员“UITextField”

这是我的错误代码。

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

完整代码:

@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)
}

在此处输入图像描述

4

3 回答 3

51

textDidChangeNotificationUITextField( 和UITextView) 的成员。

NotificationCenter.default.addObserver(
    self,
    selector: #selector(self.keyboardDidShow(notification:)),
    name: UITextField.textDidChangeNotification,
    object: nil)
于 2018-09-14T05:41:52.400 回答
6

我遇到了同样的问题,

这是最简单的解决方案:

而不是使用forName: NSNotification.Name.UITextField.textDidChangeNotification

forName:在参数中像这样使用:

NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
//Your code goes here...
        }
于 2019-06-27T10:10:56.967 回答
1
        NotificationCenter.default.addObserver(forName: Notification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
            //...
    }

在swift sdk中,所有通知名称都应该是struct的扩展名:Notification.Name

所以在使用 Notification.Name 时,你应该忽略 Class name(exc.UITextField),输入“Notification.Name”。然后输入你的一些名字(如“TextF”)并使用 esc 显示自动完成

于 2018-09-14T09:00:50.617 回答