iOS UITextField textfield empty after selecting autofill address from contacts

Viewed 556

I have a UITextField where the user enters an address and selects one of the matching locations that shows from MKLocalSearchCompleter.

If the user selects an address from the autofill option as shown below, the textField is empty. If the user then types anything after the autofill address, it works fine but right after selecting the autofill address, the textField itself is deemed empty.

Code below

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    if textField == locationTextField.textfield {
        
        let activeStr = textField.text!
        if (activeStr.length() >= 2) {
            
            if !suggestionsShowing {
                
                locationSelectorView = LocatorSelectorView (using: [], rowHeight: selectorRowHt)
                if let locationSelectorView = locationSelectorView {
                    locationSelectorView.delegate = self
                    addressSuggestionView.addSubview(locationSelectorView)
                    
                    locationSelectorView.snp.makeConstraints {
                        $0.edges.equalToSuperview()
                        $0.height.equalTo(self.selectorRowHt * CGFloat(5) + 20)
                    }
                    
                    stackview.insertArrangedSubview(addressSuggestionView, at: 1)
                    
                    suggestionsShowing = true
                }
            }
            
            self.geocoder?.appleGeocode(using: "\(textField.text!)\(string)", complete: { (error) in
                
            })
        }
    }
    return true
}

Autofill address suggestion

textField after selecting the autofill address (it's after this that it is showing activeStr is empty)

1 Answers

Instead of using:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

}

switch to:

func textFieldDidChange(_ textField: UITextField) {

}
Related