Vatsal Patel
Vatsal Patel

Reputation: 123

auto scroll for UITextView using swift (IOS app)

I cant seem to find a right solution to autoscroll UITextView using Swift.

For my app I am receiving constant data from BT, and I am updating it on a UITextView. However, when the UITextView will reach the latest updated line, I would have to manually scroll.

What I'm trying to achieve is to keep the last added line to the UITextView visible. (using swift)

Upvotes: 12

Views: 11310

Answers (3)

Arthur Stepanov
Arthur Stepanov

Reputation: 579

Swift 5 update for @SwiftArchitect answer:

let range = NSRange(location: textView.text.count - 1, length: 0)
textView.scrollRangeToVisible(range)

Upvotes: 5

Strong84
Strong84

Reputation: 1979

You could also set contentOffset:

let point = CGPoint(x: 0.0, y: (textView.contentSize.height - textView.bounds.height))
textView.setContentOffset(point, animated: true)

It will scroll to the bottom.

Upvotes: 1

SwiftArchitect
SwiftArchitect

Reputation: 48552

This will scroll to the bottom of a UITextView, with an animation:

let range = NSMakeRange(textView.text.characters.count - 1, 0)
textView.scrollRangeToVisible(range)

Upvotes: 18

Related Questions