Search code examples
iosswiftxcodeuitextfieldios-simulator

UITextField not calling editingChanged on device but works on simulator


I have a UITextField sets up in UICollectionViewCell. I've used closure to declare the UITextField as follows:

var nameTextField: UITextField = {
    let textfield = UITextField()
    textfield.backgroundColor = .clear
    textfield.borderStyle = .line
    textfield.placeholder = "Name"
    textfield.textColor = UIColor.white
    textfield.layer.borderColor = UIColor.white.cgColor
    textfield.addTarget(self, action: #selector(textfieldDidChangeValue), for: .editingChanged)
    textfield.translatesAutoresizingMaskIntoConstraints = false
    return textfield
}()

It is supposed that when textfield's content is changed, the .editingChanged event would be called and then call function textfieldDidChangeValue. It works well in iOS simulator, but not working in my real iPhone 12 Pro device. It is my first time to face problem of different behavior between simulator and real device. What is the possible fix for it? Thank you.

Xcode: Version 13.3.1 (13E500a)

iOS simulator: iOS 14.7 iPhone 13 pro

real device: iOS 14.7.1 iPhone 12 pro


Solution

  • I finally figure out why it is not working to addTarget when declaring the UITextField. Because the self is not ready when target is added. I should make the variable lazy to guarantee self is available.

    lazy var nameTextField: UITextField = {
        let textfield = UITextField()
        textfield.backgroundColor = .clear
        textfield.borderStyle = .line
        textfield.placeholder = "Name"
        textfield.textColor = UIColor.white
        textfield.layer.borderColor = UIColor.white.cgColor
        textfield.addTarget(self, action: #selector(textfieldDidChangeValue), for: .editingChanged)
        textfield.translatesAutoresizingMaskIntoConstraints = false
        return textfield
    }()