Swift add target for paste action UITextField

1.7k Views Asked by At

I have a UITextField that has a target added which performs checks on the field as the user is typing. I currently have an issue however when my code adds text to the textfield in that the text doesn't get checked. Is there a way I can solve this through .editingChanged or is there another UIControlEvent to hook into?

Code is:

NumberOutlet.addTarget(self, action: #selector(handleNumberImage), for: .editingChanged)
3

There are 3 best solutions below

1
Forest Kunecke On

The way you can handle this is by implementing the UITextViewDelegate protocol in your viewcontroller. In your viewDidLoad you would want to set the delegate of your UITextField to self.

Then, simply implement the following method, like demonstrated here:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.length > 1 {
        // Text was pasted into the text field

        // do something with pasted text
    } else {
        //typed string
    }
    return true
}
0
Chandler De Angelis On

You will want to conform to the UITextFieldDelegate protocol.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let isAddingCharacter: Bool = range.location >= 0 && range.length == 0
    let isDeletingCharacter: Bool = range.location >= 0 && range.length == 1
    var newCount: Int = textView.text.characters.count
    if isAddingCharacter {
        newCount += 1
    } else if isDeletingCharacter {
        newCount -= 1
    }
    // If the newCount is > 0, the user is entering text
    return true
}

Side note, your outlet should be named numberOutlet, not NumberOutlet. It is convention to use camel case syntax for variable names in swift.

2
ronatory On

The only way I know would be just to call the method you used as selector after you add text via code.

For example you have a method which is executed after you press a button and there you add text to your textfield and the UIControlEvent doesn't get fired here. So just call the method after adding text via code in this example after pressing a button:

@IBAction func buttonPressed(_ sender: UIButton) {
  // Note: camel case convention
  numberOutlet.text?.append("added text via code")
  // perform your check method
  handleNumberImage()
}