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

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

在这里输入图片说明

3个回答

54

textDidChangeNotificationUITextField(和 UITextView)的成员。

NotificationCenter.default.addObserver(
    self,
    selector: #selector(self.keyboardDidShow(notification:)),
    name: UITextField.textDidChangeNotification,
    object: nil)

1
我接下来要来这里 :D 看起来他们把所有的通知都移到了它们各自的类中。 - Rakesha Shastri
1
在Swift 4.2中对我有用,谢谢伙计! - Ravi

6

我遇到了同样的问题,

这里有一个最简单的解决方案:

不要使用 forName: NSNotification.Name.UITextField.textDidChangeNotification

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

NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
//Your code goes here...
        }

1
        NotificationCenter.default.addObserver(forName: Notification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
            //...
    }

在 Swift SDK 中,所有的通知名称都应该是结构体 Notification.Name 的扩展。因此,在使用 Notification.Name 时,您应该忽略类名(例如 UITextField),输入 "Notification.Name.",然后输入一些您自己的名称(比如 "TextF"),并使用 esc 键来显示自动完成。

1
在 Swift 4.2 中,Notification.Name.UITextFieldTextDidChange 并不存在。大多数通知并非属于 Notification.Name(同样也是基于 Swift 4.2)。 - rmaddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接