2

How should I scroll to the bottom of a UITextView? My previous implementation, which I took from a previous post here on stackoverflow, stopped working when I updated to Swift 4.

My program regularly pastes new information to a UITextView (consoleZe) and then scrolls to the bottom of it so the latest update is always visible, console-style. My updateConsole method is basically this:

    if let tempString = consoleZe.text {
        currentText = tempString
    }

    consoleZe.text = currentText + "A message!\n"

    let bottom = NSMakeRange(consoleZe.text.characters.count - 1, 1)
    consoleZe.scrollRangeToVisible(bottom)
    print("Scrolled to \(bottom)")

In Swift 3, this worked great! Now in Swift 4, it only scrolls sometimes.

I can't figure out why/when it scrolls or doesn't scroll. I added that print statement to try and figure it out. The statement appears on Swift's console with a newly updated "bottom" every time... but in the simulator it only actually scrolls every once in a while. If I send messages one at a time, the screen miraculously scrolls after 10 messages, after 22 messages, 20 messages, 20 messages, 21 messages...

Is there a new requirement or quirk about scrollRangeToVisible?

More importantly, am I doing this wrong?

Is there some other (more efficient) way to ask a UITextView to always scroll to the bottom after I change its text value?

Beagley
  • 73
  • 1
  • 7
  • 1
    I have a similar problem, where the textView will only scroll to the bottom if the last character is a newline (\n). So I worked around this by adding a newline at the end of every update (and removing the last character in the textView before every update). – hoiberg Dec 15 '17 at 15:44

1 Answers1

0

Check out this answer.

With Swift 4, something like the following seems to work for me (in iOS 9-12):

let textViewBottom = NSMakeRange(textView.text.count - 1, 1)
textView.scrollRangeToVisible(textViewBottom)
textView.isScrollEnabled = false
textView.isScrollEnabled = true
ko la
  • 431
  • 4
  • 9