Allow cursor selection anywhere in UITextView

I have one UITextView that allows me to write multiple lines of text.

How can I let users select letters between words without long press?

Currently, when using the touch screen to select characters between words, the cursor either goes at the beginning or end of the word:

Example: clicking on 'c' moves the cursor to the end of the word

cursor at the end

Example: clicking on 'a' moves the cursor to the beginning of a word

start cursor

Desired cursor behavior: select anywhere in the text enter image description here

The function of allowing text selection anywhere (without long pressing + magnifying glass) is found in many iOS code editing applications such as Coda and Pythonista .

+5
source share
1 answer

It is not a difficult task to achieve.

I will present that the problem with this approach is coherence. Remember that your users use their fingers, not styles. The finger has a large surface area, and getting into the exact area of ​​the pixels is quite difficult, especially with small text. I suggest playing not in the simulator, where you have an exact pointing device, but on the device.

The first task is to disable the default behavior or UITextView . This is not a difficult task - you can β€œattack” the problem at the touchesBegan:withEvent: level, where you will need to understand what it is about (single tap against panning or long press) or the gesture recognizer level, where you disable text-type private gesture recognizers, which specifically handle the movement of the cursor in case of pressing (compared to other types of touch). I did the latter for different projects, and it is possible. You can also try the approach without disabling the default behavior, but then the cursor may flicker. Try and decide.

Now to achieve what you need. Get the touch point somehow (using the UIResponder API or gesture recognizer). Remember that a text view is a scroll view that includes a large view in which the content is embedded. You must convert this touch point from the text view coordinate system to the internal view coordinate system using the convertPoint: API. After that, you can use the text view layout manager to get the index of the character at the touch point:

 NSUInteger chIdx = [self characterIndexForPoint:touchPoint inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:NULL]; 

This index can be used to position the text view cursor using the selectedRange property.

+3
source

Source: https://habr.com/ru/post/1261813/


All Articles