0

I’m making an app where the user needs to be able to type long pieces of text (like a journal article) but shouldn’t be allowed to edit it until a later stage in the app.

So I need to allow the user to type in a UITextField in a ‘forwards’ direction but completely disable being able to select the text further up and edit it (or even use the backspace).

There are plenty of answers already around disabling the selecting/editing (for example when using a picker view as the input e.g. Disabling user input for UITextfield in swift) but I can’t find anything that would allow for the behaviour I want and despite trying variations of the text field delegate methods I really cant get my head around where to go next at the moment.

I’m thinking I need to do 3 things

1) allow editing of the text field 2) disable selecting (by tapping for example) the text field 3) disable the backspace key?

nc14
  • 539
  • 1
  • 8
  • 26
  • Your use case sounds really bad. Why do you need it like this? What if the user makes a typo? Also, people are used to using a text view with editing, so they will naturally use backspace and type before they even realize it has been disabled, leading to even more errors. – Rakesha Shastri Jun 01 '19 at 15:45
  • Hi - it’s very specific to writing first drafts of creative written works. There is a mode that will disallow “editing while you go” which is a very common problem for writers (because it can be edited later) – nc14 Jun 01 '19 at 16:04
  • You still haven't answered my other question (which is the important one). I have never come across such a use case anywhere. But maybe it exists in your area of work. Maybe if you could show us an example, like a website which does it or something, then we could understand better i guess. – Rakesha Shastri Jun 01 '19 at 16:07

1 Answers1

1

As far as I understand this code can help you:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return textField.text!.count <= range.location
}

this method is from the delegate of your UITextField.

Also, you can add more complex checks with range and replacement string. Like if you want to add more text or you want to delete text.

m1sh0
  • 2,236
  • 1
  • 16
  • 21
  • 1
    You probably want `return range.location >= textField.text!.utf16.count && range.length == 0`. This ensures the cursor is at the end and its just a cursor and not a selection. Also note the use of `utf16.count` instead of just `count`. This is important since the range is based on the NSString representation of the text. – rmaddy Jun 01 '19 at 16:52