简体   繁体   中英

“Manually” handling text and cursor position of UITextView breaks when there are multiple lines

I have a narrow UITextView (about 1 line in height) to which I only add text programmatically, setting the text property of it as I click buttons. I also handle the cursor position manually, setting the selectedRange as the text changes. All works great as long as I have only one line of text.

When I have two or more lines of text and try to insert text at the first line, the text is inserted correctly and the cursor position is still at the right place but the UITextView scrolls to the bottom. When I then add another piece of text at the top it scrolls up to the "correct" position. This pattern then repeats for every entered piece of text at a line other than the last, making the UITextView scroll up and down for every button pressed.

I also tried calling UITextView scrollRangeToVisible: passing the selectedRange property as argument after setting the new text. That didn't work either.

I finally tried setting selectedRange after a 0.5 s delay after I set the text . Then it works as it should, but only after the UITextView has first been scrolled down to the bottom for 0.5 s. This seems to indicate that the setText method of UITextView is asynchronous in some way, and completes after I have already set selectedRange or called scrollRangeToVisible , and readjusts the UITextView to what it believes is the desired.

Can anyone tell me what is going on, and how I can get around the problem.

Thanks!

The auto scroll behavior of UITextField s can be annoying and difficult to harness at times.

Do you need the user to manually edit the text? If not, use a multiline UILabel .

If yes, also use a multiline UILabel and exchange it on the fly against a UITextView once the user taps. Change it back on didEndEditing . This techniques has worked well for me in table views.

I solved the problem! When starting in the maze of creating a custom input view, I began implementing UITextInput and I found that the UITextInput protocol declares many interesting methods. And what is awesome is that UITextView implements that protocol. So even though it's not in the immediate UITextView API reference, you can call all UITextInput methods on your UITextView . For instance insertText: (from UIKeyInput protocol) and replaceRange:withText: . They made it much more flexible to programmatically work with a UITextView . Hope this can help someone else too!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM