restrict paste in textfield in swift

To restrict paste operation in a UITextField, we can use the add target method of the UITextField. In the target method, we can get the string that the user is trying to paste and return 'false' to discard the pasted string. Here's an example code:

main.swift
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

@objc private func textFieldDidChange(_ textField: UITextField) {
    //get the string that user is trying to paste
    guard let pastedString = UIPasteboard.general.string else {
        return
    }
    
    //check if the string is empty, if true return 'true' to allow paste
    if pastedString.isEmpty {
        return true
    }
    
    //return 'false' to discard the pasted string
    return false
}
501 chars
17 lines

In the snippet above, we use the textFieldDidChange method as the target action for the editingChanged event. This method gets the pasted string from the UIPasteboard and checks if it's empty. If the pasted string is not empty, it returns 'false' to discard the pasted string.

gistlibby LogSnag