为什么在我的自定义 Swift 类中没有调用我的选择器函数

问题描述

我有一个名为 Utilities 的自定义类,它有一个名为 createCustomeTextField方法,用于创建自定义文本字段。自定义文本字段为所有事件添加一个目标,但当我在文本字段中键入时,它不会调用目标 c 选择器函数

这是我的自定义类:

class Utilities {
    
    static func createCustomInputContainerView(withImage image: UIImage,andTextField textField: UITextField) -> UIView {
        
        let view = UIView()
        let iv = UIImageView()
        view.setHeight(to: 50)
        iv.image = image
        view.addSubview(iv)
        iv.anchor(left: view.leftAnchor,bottom: view.bottomAnchor,paddingBottom: 8.0,width: 24.0,height: 24.0)
        
        view.addSubview(textField)
        textField.anchor(left: iv.rightAnchor,right: view.rightAnchor,paddingLeft: 8.0,paddingBottom: 8.0)
        
        let dividerView = UIView()
        dividerView.backgroundColor = .white
        view.addSubview(dividerView)
        dividerView.anchor(left: view.leftAnchor,height: 0.75)
        return view
    }
    
    func createCustomTextField(withPlaceholder placeholder: String) -> UITextField {
        let tf = UITextField()
        tf.textColor = .white
        tf.font = UIFont.systemFont(ofSize: 16.0)
        tf.attributedplaceholder = NSAttributedString(string: placeholder,attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
        tf.addTarget(self,action: #selector(handleEditingDidBegin(sender:)),for: .allEvents)
        return tf
    }
    
    @objc func handleEditingDidBegin(sender: Any) {
        print("DEBUG: Got here")
    }
}

这是我的 Utilities 实例的创建位置。它在一个视图控制器类中。

...
    private lazy var emailContainerView: UIView = {
        let view = Utilities.createCustomInputContainerView(withImage: #imageLiteral(resourceName: "ic_mail_outline_white_2x-1"),andTextField: emailTextField)
        return view
    }()
    
    private lazy var passwordContainerView: UIView = {
        let view = Utilities.createCustomInputContainerView(withImage: #imageLiteral(resourceName: "ic_lock_outline_white_2x"),andTextField: passwordTextField)
        return view
    }()
    
    private let emailTextField: UITextField = {
        let tf = Utilities().createCustomTextField(withPlaceholder: "Email")
        return tf
    }()

    private let passwordTextField: UITextField = {
        let tf = Utilities().createCustomTextField(withPlaceholder: "Password")
        tf.isSecureTextEntry = true
        return tf
    }()
...

解决方法

将 Utilities 设为单例类并设置文本字段的标签属性。