I am new to iOS development. I am working with view with multiple TextField and TextView.I am trying to move the view up to avoid keyboard is hiding the Editing TextField,TextView content.The below code is working fine for all TextFields but it is not moving view up when TextView is Edited.Hope you understand my problem. Thanks in advance.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
var keybordenabled = false
@objc func keyboardWillShow(notification: NSNotification) {
if(keybordenabled == false){
adjustInsetForKeyboardShow(show: true, notification: notification)
keybordenabled = true
}
}
@objc func keyboardWillHide(notification: NSNotification) {
keybordenabled = false
adjustInsetForKeyboardShow(show: false, notification: notification)
}
func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
let userInfo = notification.userInfo ?? [:]
let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let adjustment = (keyboardFrame.height * (show ? 1 : -1)) + 20
scrollView.contentInset.bottom += adjustment
scrollView.scrollIndicatorInsets.bottom += adjustment
self.view.layoutIfNeeded()
}
func textViewDidBeginEditing(_ textView: UITextView)
{
if (textView.text == "Enter comment here...")
{
textView.text = ""
textView.textColor = .black
}
textView.becomeFirstResponder()
}
func textViewDidEndEditing(_ textView: UITextView)
{
if (textView.text == "")
{
textView.text = "Enter comment here..."
textView.textColor = .lightGray
}
textView.resignFirstResponder()
}