我有一个滚动视图,其中包含许多文本字段作为子视图,我希望选定的文本字段(_activeField)在键盘出现时向上滚动。
- (void) keyboardUP:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height + 10, 0.0);
_scroller.contentInset = contentInsets;
_scroller.scrollIndicatorInsets = contentInsets;
CGRect aRect = App_Delegate.window.frame;
aRect.size.height -= kbSize.height;
CGRect rect = [_activeField convertRect:_activeField.frame fromView:App_Delegate.window];
if (!CGRectContainsPoint(aRect, rect.origin) )
{
[_scroller scrollRectToVisible:rect animated:YES];
}
}
此代码适用于iOS 10,但是在iOS 11中,它不起作用,"scrollRectToVisible"即使其内容大小正确也不会滚动ScrollView。
我不确定
- (void) keyboardUP:(NSNotification *)notification
但已经看到了类似的问题
- (void)handleKeyobardDidShowNotification:(NSNotification *)notification
看起来这不再在 iOS 11 的主线程上运行。
尝试在主线程上运行你调用的scrollRectToVisible,如下所示
dispatch_async(dispatch_get_main_queue(), ^{
[_scroller scrollRectToVisible:targetPosition animated:YES];
});
这是此问题的副本。
使用UIKeyboardFrameEndUserInfoKey
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
print(keyboardSize)
}
}
和 ObjC
- (void)keyboardWillShow:(NSNotification *)notification {
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
}