Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView starts at Bottom or Middle of the text

I'll get right to it. I have a UItextView placed in my view that when needs to scroll to see all the text (when a lot of text is present in the textView) the textView starts in the middle of the text sometimes and the bottom of the text other times.

enter image description here

Editing is not enabled on the textView. I need a way to force the textView to start at the top, every time. I saw some questions somewhat like this where other people used a content offset, but I do not really know how that works or if it would even be applicable here.

Thanks for your help.

like image 697
Alex Wulff Avatar asked Dec 23 '14 14:12

Alex Wulff


4 Answers

That did the trick for me!

Objective C:

[self.textView scrollRangeToVisible:NSMakeRange(0, 0)];

Swift:

self.textView.scrollRangeToVisible(NSMakeRange(0, 0))

Swift 2 (Alternate Solution)

Add this override method to your ViewController

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    textView.setContentOffset(CGPointZero, animated: false)
}

Swift 3 & 4 (syntax edit)

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()

  textView.contentOffset = .zero
}
like image 140
David Cruz Avatar answered Nov 12 '22 23:11

David Cruz


All of the answers above did not work for me. However, the secret turns out to be to implement your solution within an override of viewDidLayoutSubviews, as in:

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()

  welcomeText.contentOffset = .zero
}

HTH :)

like image 35
zeeple Avatar answered Nov 13 '22 01:11

zeeple


In Swift 2

You can use this to make the textView start from the top:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    myTextView.setContentOffset(CGPointZero, animated: false)
}

Confirmed working in Xcode 7.2 with Swift 2

like image 14
Nick89 Avatar answered Nov 12 '22 23:11

Nick89


Try this below code -

if ( [self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]){
     self.automaticallyAdjustsScrollViewInsets = NO;         
}

Or you can also set this property by StoryBoard -

Select ViewController then select attributes inspector now unchecked Adjust Scroll View Insets.

like image 13
keshav vishwkarma Avatar answered Nov 13 '22 01:11

keshav vishwkarma