102
votes

OK, I'm having some problem with the UITextView. Here's the issue:

I add some text to a UITextView. The user then double clicks to select something. I then change the text in the UITextView (programatically as above) and the UITextView scrolls to the bottom of the page where there is a cursor.

However, that is NOT where the user clicked. It ALWAYS scrolls to the bottom of the UITextView regardless of where the user clicked.

So here's my question: How do I force the UITextView to scroll to the top every time I change the text? I've tried contentOffset and scrollRangeToVisible. Neither work.

Any suggestions would be appreciated.

30

30 Answers

153
votes
UITextView*note;
[note setContentOffset:CGPointZero animated:YES];

This does it for me.

Swift version (Swift 4.1 with iOS 11 on Xcode 9.3):

note.setContentOffset(.zero, animated: true)
70
votes

If anyone has this problem in iOS 8, I found that just setting the UITextView's text property, then calling scrollRangeToVisible with an NSRange with location:0, length:0, worked. My text view was not editable, and I tested both selectable and not selectable (neither setting affected the result). Here's a Swift example:

myTextView.text = "Text that is long enough to scroll"
myTextView.scrollRangeToVisible(NSRange(location:0, length:0))
46
votes

And here is my solution...

    override func viewDidLoad() {
        textView.scrollEnabled = false
        textView.text = "your text"
    }

    override func viewDidAppear(animated: Bool) {
        textView.scrollEnabled = true
    }
39
votes

Calling

scrollRangeToVisible(NSMakeRange(0, 0))

works but call it in

override func viewDidAppear(animated: Bool)
29
votes

I was using attributedString in HTML with text view not editable. Setting the content offset did not work for me either. This worked for me: disable scroll enabled, set the text and then enable the scrolling again

[yourTextView setScrollEnabled:NO];
yourTextView.text = yourtext;
[yourTextView setScrollEnabled:YES];
19
votes

Since none of these solutions worked for me and I wasted way too much time piecing together solutions, this finally solved it for me.

override func viewWillAppear(animated: Bool) {
    dispatch_async(dispatch_get_main_queue(), {
        let desiredOffset = CGPoint(x: 0, y: -self.textView.contentInset.top)
        self.textView.setContentOffset(desiredOffset, animated: false)
    })
}

This is really silly that this is not default behavior for this control.

I hope this helps someone else out.

18
votes

I'm not sure if I understand your question, but are you trying to simply scroll the view to the top? If so you should do

[textview scrollRectToVisible:CGRectMake(0,0,1,1) animated:YES];

14
votes

For iOS 10 and Swift 3 I did:

override func viewDidLoad() {
    super.viewDidLoad()
    textview.isScrollEnabled = false
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    textView.isScrollEnabled = true
}

Worked for me, not sure if you're having the problem with the latest version of Swift and iOS.

10
votes

I have an updated answer which will have the textview appear properly, and without the user experiencing a scroll animation.

override func viewWillAppear(animated: Bool) {
    dispatch_async(dispatch_get_main_queue(), {
        self.introductionText.scrollRangeToVisible(NSMakeRange(0, 0))
    })
9
votes

This is how it worked on iOS 9 Release so as the textView is scrolled on top before appearing on screen

- (void)viewDidLoad
{
    [super viewDidLoad];
    textView.scrollEnabled = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    textView.scrollEnabled = YES;
}
9
votes

That's how I did it

Swift 4:

extension UITextView {

    override open func draw(_ rect: CGRect)
    {
        super.draw(rect)
        setContentOffset(CGPoint.zero, animated: false)
    }

 }
8
votes

This worked for me

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    DispatchQueue.main.async {
      self.textView.scrollRangeToVisible(NSRange(location: 0, length: 0))
    }
  }
6
votes

Try this to move the cursor to the top of the text.

NSRange r  = {0,0};
[yourTextView setSelectedRange:r];

See how that goes. Make sure you call this after all your events have fired or what ever you are doing is done.

6
votes

My issue is to set textView to scroll to top when view appeared. For iOS 10.3.2, and Swift 3.

Solution 1:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // It doesn't work. Very strange.
    self.textView.setContentOffset(CGPoint.zero, animated: false)
}
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // It works, but with an animation effection.
    self.textView.setContentOffset(CGPoint.zero, animated: false)
}

Solution 2:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // It works.       
    self.textView.contentOffset = CGPoint.zero
}
6
votes

just you can use this code

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    textView.scrollRangeToVisible(NSMakeRange(0, 0))
}
6
votes

I had to call the following inside viewDidLayoutSubviews (calling inside viewDidLoad was too early):

    myTextView.setContentOffset(.zero, animated: true)
5
votes

Combined the previous answers, now it should work:

talePageText.scrollEnabled = false
talePageText.textColor = UIColor.blackColor()
talePageText.font = UIFont(name: "Bradley Hand", size: 24.0)
talePageText.contentOffset = CGPointZero
talePageText.scrollRangeToVisible(NSRange(location:0, length:0))
talePageText.scrollEnabled = true
5
votes
[txtView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];

This line of code works for me.

4
votes

Swift 2 Answer:

textView.scrollEnabled = false

/* Set the content of your textView here */

textView.scrollEnabled = true

This prevents the textView from scrolling to the end of the text after setting it.

4
votes

In Swift 3:

  • viewWillLayoutSubviews is the place to make changes. viewWillAppear should work as well, but logically, layout should be perform in viewWillLayoutSubviews.

  • Regarding methods, both scrollRangeToVisible and setContentOffset will work. However, setContentOffset allows animation to be off or on.

Assume the UITextView is named as yourUITextView. Here's the code:

// Connects to the TextView in the interface builder.
@IBOutlet weak var yourUITextView: UITextView!

/// Overrides the viewWillLayoutSubviews of the super class.
override func viewWillLayoutSubviews() {

    // Ensures the super class is happy.
    super.viewWillLayoutSubviews()

    // Option 1:
    // Scrolls to a range of text, (0,0) in this very case, animated.
    yourUITextView.scrollRangeToVisible(NSRange(location: 0, length: 0))

    // Option 2:
    // Sets the offset directly, optional animation.
    yourUITextView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
}
3
votes

This worked for me. It is based on RyanTCBs answer but it is the Objective-C variant of the same solution:

- (void) viewWillAppear:(BOOL)animated {
    // For some reason the text view, which is a scroll view, did scroll to the end of the text which seems to hide the imprint etc at the beginning of the text.
    // On some devices it is not obvious that there is more text when the user scrolls up.
    // Therefore we need to scroll textView to the top.
    [self.textView scrollRangeToVisible:NSMakeRange(0, 0)];
}
3
votes
-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];

    [textview setContentOffset:CGPointZero animated:NO];
}
3
votes
-(void) viewDidAppear:(BOOL)animated{
[mytextView scrollRangeToVisible:NSMakeRange(0,0)];}

- (void)viewWillAppear:(BOOL)animated{
[mytextView scrollRangeToVisible:NSMakeRange(0,0)];}
  • ViewWillappear will do it instantly before user can notice, but ViewDidDisappear section will animate it lazily.
  • [mytextView setContentOffset:CGPointZero animated:YES]; does NOT work sometimes(I don't know why), so use scrollrangetovisible rather.
2
votes
[self.textView scrollRectToVisible:CGRectMake(0, 0, 320, self.textView.frame.size.height) animated:NO];
2
votes

Problem solved: iOS = 10.2 Swift 3 UITextView

I just used the following line:

displayText.contentOffset.y = 0
2
votes

I had the problem, but in my case textview is the subview of some custom view and added it to ViewController. None of the solution worked for me. To solve the problem added 0.1 sec delay and then enabled scroll. It worked for me.

textView.isScrollEnabled = false
..
textView.text = // set your text here

let dispatchTime = DispatchTime.now() + 0.1
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
   self.textView.isScrollEnabled = true
}
1
votes

For me fine works this code:

    textView.attributedText = newText //or textView.text = ...

    //this part of code scrolls to top
    textView.contentOffset.y = -64
    textView.scrollEnabled = false
    textView.layoutIfNeeded() //if don't work, try to delete this line
    textView.scrollEnabled = true

For scroll to exact position and show it on top of screen I use this code:

    var scrollToLocation = 50 //<needed position>
    textView.contentOffset.y = textView.contentSize.height
    textView.scrollRangeToVisible(NSRange.init(location: scrollToLocation, length: 1))

Setting contentOffset.y scrolls to the end of text, and then scrollRangeToVisible scrolls up to value of scrollToLocation. Thereby, needed position appears in first line of scrollView.

1
votes

For me in iOS 9 it stopped to work for me with attributed string with method scrollRangeToVisible (the 1 row was with bold font, other rows were with regular font)

So I had to use:

textViewMain.attributedText = attributedString
textViewMain.scrollRangeToVisible(NSRange(location:0, length:0))
delay(0.0, closure: { 
                self.textViewMain.scrollRectToVisible(CGRectMake(0, 0, 10, 10), animated: false)
            })

where delay is:

func delay(delay:Double, closure:()->Void) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}
1
votes

Try to use this 2 lines solution:

view.layoutIfNeeded()
textView.contentOffset = CGPointMake(textView.contentInset.left, textView.contentInset.top)
1
votes

Here are my codes. It works fine.

class MyViewController: ... 
{
  private offsetY: CGFloat = 0
  @IBOutlet weak var textView: UITextView!
  ...

  override viewWillAppear(...) 
  {
      ...
      offsetY = self.textView.contentOffset.y
      ...
  }
  ...
  func refreshView() {
      let offSetY = textView.contentOffset.y
      self.textView.setContentOffset(CGPoint(x:0, y:0), animated: true)
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
        [unowned self] in
        self.textView.setContentOffset(CGPoint(x:0, y:self.offSetY), 
           animated: true)
        self.textView.setNeedsDisplay()
      }
  }