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 conten开发者_JAVA百科tInsets = 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.
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!
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.
I had a UIScrollView that would scroll in both dimensions, and it had a single subview. The contentSize of the scroll view didn't match the bounds size of the subview, so scrollRectToVisible
(with the provided CGRect in the subview's coordinate space) didn't scroll to the right place. Converting the coordinate space made it work as intended:
let targetPoint = CGPoint(x: 200, y: 200)
let scrollTarget = contentView.convert(targetPoint, to: scrollView)
let targetRect = CGRect(center: scrollTarget, size: .init(width: 150, height: 150))
scrollView.scrollRectToVisible(targetRect, animated: false)
精彩评论