3

I'm attempting to vertically align a UITextView by setting the content offset appropriately.

I'm calling the following code when I change the text of my textView:

- (void)setCenterVerticalAlignmentForTextView:(UITextView*)textView {
    CGFloat topCorrect = ([textView bounds].size.height - [textView contentSize].height * [textView zoomScale])/2.0;
    topCorrect = (topCorrect < 0.0 ? 0.0 : topCorrect );
    textView.contentOffset = CGPointMake(0,-topCorrect);
}

This works perfectly the first time the UIView is shown on the screen.

However, if I change the text inside the textView and call this function again, the last line of the function which sets the contentOffset doesn't seem to make any difference. The content offset becomes (0,0) no matter what I set.

Do I need to do something to reset the contentOffset or contentInset before I attempt to reset it?

Thanks guys, any help much appreciated.

Duncs

theDuncs
  • 4,649
  • 4
  • 39
  • 63

2 Answers2

0

This answer really helped me. It's not pretty, but it worked! First reset by setting 0,0.

CGPoint offset = CGPointMake(0, self.textView.contentSize.height - 
                                self.textView.frame.size.height);
[self.textView setContentOffset: CGPointMake(0,0) animated:NO]; 
[self.textView setContentOffset:bottomOffset animated:YES]; 
Community
  • 1
  • 1
Epaga
  • 38,231
  • 58
  • 157
  • 245
0
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;

use this deligate it will call if any text change happen in the textview can code in that

Rama Rao
  • 1,043
  • 5
  • 22
  • Thanks, but this doesn't fix the problem. This method is only called when the user changes the text within the textview and in this case it is not a user-updatable textview. Even if this were called, I don't think it addresses the problem of the contentOffset not resetting correctly. Thanks anyway. – theDuncs Feb 28 '12 at 12:22
  • where u r calling that function mean viewdidload or view will appear – Rama Rao Feb 28 '12 at 12:36
  • I'm calling it whenever I programatically change the content of the uitextview. That happens after various button clicks. – theDuncs Feb 28 '12 at 17:13