Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScrollRectToVisible Not Working As Intended

I have a view that has text fields ranging from the top of the screen to the bottom of the screen. Obviously, the bottom text fields get covered up by the keyboard when it pops up, so I set out to get rid of this problem.

I register for notifications in the viewDidLoad method, then when the UIKeyboardDidShowNotification is sent, this method is called:

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    [scrollView scrollRectToVisible:activeField.frame animated:YES];
}

The problem is nothing is getting scrolled at all, let alone scrolled to visible. What am I missing here?

All of my text fields are inside of a scroll view, etc.

Thanks in advance.

like image 756
Baub Avatar asked Aug 26 '11 17:08

Baub


2 Answers

This is a similar post where scrollRectToVisible: is not working correctly, and there is a solution by making sure the contentSize is set correctly. Hope that Helps!

like image 61
msgambel Avatar answered Nov 11 '22 15:11

msgambel


Sending a message to myself in the future: Your contentSize width is 0.

When the width of contentSize is 0, scrollRectToVisible has no effect.

Also, your contentSize width is 0 because of AutoLayout.

See https://developer.apple.com/library/archive/technotes/tn2154/_index.html

Also, it's because you're not explicitly setting the width of the content view, but are doing something silly like centering the content view within the scroll view, and maybe it's the case that UIScrollView isn't clever enough to figure out how to set contentSize in the context of Auto Layout in this situation.

like image 42
Drew Avatar answered Nov 11 '22 15:11

Drew