4

i have multiple textField and textView in scrollView in my viewController. i handle keyboard show and hide with these codes:

i added these line of code in 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)

and also these 2 function:

@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
}

everything is ok when i start to edit a textField. but it does not work with textView and has problem to scroll to active textView.

how can i fix it?

Sajjad
  • 1,536
  • 2
  • 17
  • 31

2 Answers2

4

The reason of this issue is explained here, so if you want to use UITextView inside a UIScrollView then uncheck the Scrolling Enabled from right menu inspector or set it False from the code.

enter image description here

Rana Ijaz
  • 458
  • 5
  • 14
0

Here is a tricky way to scroll to a TextView embedded in a ScrollView when a keyboard is showing up and don't need to disable the scroll behavior. Implement the UITextViewDelegate's method textViewShouldBeginEditing(_:) as the following snippets:

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

You also need to listen to the notifications for keyboard appearing and implement the logic as usual.

ovo
  • 1,904
  • 13
  • 26