代码之家  ›  专栏  ›  技术社区  ›  Krunal

'类型'通知。名称'没有成员'UITextField'

  •  7
  • Krunal  · 技术社区  · 6 年前

    在swift4.2中,出现以下错误,这在swift4中运行良好。

    '类型'通知。名称'没有成员'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)
    }
    

    enter image description here

    3 回复  |  直到 6 年前
        1
  •  48
  •   rmaddy    6 年前

    textDidChangeNotification 是…的成员 UITextField (和 UITextView

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(self.keyboardDidShow(notification:)),
        name: UITextField.textDidChangeNotification,
        object: nil)
    
        2
  •  4
  •   iHarshil l0gg3r    5 年前

    我也面临同样的问题,

    下面是最简单的解决方案:

    forName: NSNotification.Name.UITextField.textDidChangeNotification

    像这样用在 forName: 参数:

    NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
    //Your code goes here...
            }
    
        3
  •  1
  •   Sven Shao    6 年前
            NotificationCenter.default.addObserver(forName: Notification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
                //...
        }
    

    在swift sdk中,所有通知名称都应该是struct:通知。名称

    推荐文章