swift 键盘隐藏/显示通知时UITextView的scrollView问题

dfty9e19  于 2023-05-27  发布在  Swift
关注(0)|答案(2)|浏览(260)

我在viewController中有多个textFieldtextView以及scrollView。我用这些代码处理键盘显示和隐藏:
我在viewDidLoad中添加了以下代码行:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:UIResponder.keyboardWillHideNotification, object: nil)

还有这两个功能:

@objc func keyboardWillShow(notification:NSNotification){
    guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
        
    let keyboardScreenEndFrame = keyboardValue.cgRectValue
    let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
    let bottom = keyboardViewEndFrame.height - view.safeAreaInsets.bottom + 16
        
    self.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottom , right: 0)
}
    
@objc func keyboardWillHide(notification:NSNotification){
    self.scrollView.contentInset = UIEdgeInsets.zero
}

当我开始编辑文本字段时,一切正常。但它不适用于textView,并且滚动到活动textView时有问题。
怎么修理?

eyh26e7m

eyh26e7m1#

这个问题的原因解释为here,所以如果你想在UIScrollView中使用UITextView,然后从右菜单检查器中取消选中Scrolling Enabled,或者从代码中设置为False

9jyewag0

9jyewag02#

这里有一个技巧性的方法,当键盘出现时,滚动到嵌入在ScrollView中的TextView,并且不需要禁用滚动行为。按照以下代码片段实现UITextViewDelegate的方法textViewShouldBeginEditing(_:)

extension MyViewController: UITextViewDelegate {
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            self.scrollView.scrollViewToVisible(self.targetView)
        }
        
        return true
    }
}

您还需要收听键盘出现的通知并像往常一样实现逻辑。

相关问题