Ios 当视图控制器内部有滚动视图时处理键盘事件
在我的项目中,有一个视图控制器嵌入在选项卡栏控制器中。此视图控制器有一个显示抽屉的按钮(视图中的幻灯片)。我正在使用第三方库进行此操作。从现在起,我将在面板视图控制器中引用它 此面板视图控制器是一个内部带有滚动视图的简单视图控制器。scrollview中有一个堆栈视图。所有其他子视图(绿色和橙色视图)都通过堆栈视图进行布局 橙色视图的底部有一个文本字段。我编写了下面的代码来处理键盘事件,将文本字段移到键盘上方并向下移动Ios 当视图控制器内部有滚动视图时处理键盘事件,ios,swift,uiscrollview,ios13,uikeyboard,Ios,Swift,Uiscrollview,Ios13,Uikeyboard,在我的项目中,有一个视图控制器嵌入在选项卡栏控制器中。此视图控制器有一个显示抽屉的按钮(视图中的幻灯片)。我正在使用第三方库进行此操作。从现在起,我将在面板视图控制器中引用它 此面板视图控制器是一个内部带有滚动视图的简单视图控制器。scrollview中有一个堆栈视图。所有其他子视图(绿色和橙色视图)都通过堆栈视图进行布局 橙色视图的底部有一个文本字段。我编写了下面的代码来处理键盘事件,将文本字段移到键盘上方并向下移动 @objc private func didReceiveKeyboard
@objc private func didReceiveKeyboardNotification(_ notification: Notification) {
if
let userInfo = notification.userInfo,
let endValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue,
let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double,
let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
// Transform the keyboard's frame into our view's coordinate system
let endRect = view.convert(endValue.cgRectValue, from: view.window)
// Find out how much the keyboard overlaps the scroll view
// We can do this because our scroll view's frame is already in our view's coordinate system
let keyboardOverlap = scrollView.frame.maxY - endRect.origin.y
// Set the scroll view's content inset to avoid the keyboard
// Don't forget the scroll indicator too!
scrollView.contentInset.bottom = keyboardOverlap
scrollView.verticalScrollIndicatorInsets.bottom = keyboardOverlap
UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: curve), animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
键盘关闭后,视图应移回初始位置。问题是scrollview没有重置到原始位置。textfield最终低于您看到的初始位置
我想不出这里有什么问题
试试看。我有一个类似的问题,这解决了它没有任何代码,它只是工作。你的
direceivekeyboardnotification
方法中的问题。您正在使用相同的方法来处理显示/隐藏键盘,并且在这两种情况下,您都会使scrollView.contentInset.bottom=keyboardOverlap
,因此在键盘将隐藏后,您的插入将设置为0。这是更正确的方法:
if notification.name == UIResponder.keyboardWillHideNotification {
let inset = tabBarController?.tabBar.frame.size.height as! CGFloat //Tabbar height
scrollView.contentInset.bottom = inset
scrollView.verticalScrollIndicatorInsets.bottom = inset
}
if notification.name == UIResponder.keyboardWillShowNotification {
scrollView.contentInset.bottom = keyboardOverlap
scrollView.verticalScrollIndicatorInsets.bottom = keyboardOverlap
}