1

I am creating a phone number formatter and to not break my background formatting logic, I want users to be able to only type numbers and delete (Number keyboard), and not move throughout the UITextfield.text with his touch. This will also prevent the user from pasting text, which is something I want to prevent as well. So, in short, I want the user to fill the phone number and should he/she ever need to correct a single character, he/she should delete all numbers after such character to be able to delete the mistaken one.

Therefore, text should be editable but not selectable (and cursor not movable).

My guess is that it could be something inside this method.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
rmaddy
  • 314,917
  • 42
  • 532
  • 579
rgoncalv
  • 5,825
  • 6
  • 34
  • 61
  • 5
    That seems like the perfect way to create a terrible user experience... – Dávid Pásztor Sep 19 '17 at 13:40
  • What do you mean by "background formatting"? If your text field formatting can't handle the user moving the cursor or deleting or pasting text, then you are doing it wrong. Make the user's experience better instead of making your job easier. – rmaddy Sep 19 '17 at 14:32
  • Possible duplicate of [Prevent user from setting cursor position on UITextField](https://stackoverflow.com/questions/16419095/prevent-user-from-setting-cursor-position-on-uitextfield) – pkamb Sep 19 '21 at 01:02

2 Answers2

0

To prevent user from entering anything in between of the text in textField

extension ViewController : UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if range.location + range.length < (textField.text?.characters.count)! {
            return false
        }
        else {
            return true
        }
    }
}

The code above will not prevent user from entering text characters its just to explain how to prevent user from editing the user entered text and allowing user to modify string only at end

EDIT:

This will also prevent the user from pasting text, which is something I want to prevent as well

In order to prevent user from pasting anything on textField, you need to subclass the textField and override canPerformAction

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(UIResponderStandardEditActions.paste(_:)) {
        return false
    }
    return super.canPerformAction(action, withSender: sender)
}
Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78
0

May be you can create a subclass and disable actions with this:

class MyTextField: UITextField{
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}
Alexkater
  • 76
  • 4