Keyboard hides UITextView swift 2

I use UITableViewwith two custom cells, I have custom cells with UITextViewand UITextField, I try to move the edited field when it is hiding on the keyboard at the top of the keyboard, here is my code for viewDidLoad:

 override func viewDidLoad() {
        super.viewDidLoad()
 let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIKeyboardWillShowNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIKeyboardWillHideNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIKeyboardWillChangeFrameNotification, object: nil)

    }

and here is the function called when the keyboard notification is sent:

func adjustForKeyboard(notification: NSNotification) {
    let userInfo = notification.userInfo!

    let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)

    if notification.name == UIKeyboardWillHideNotification {
        myTableView.contentInset = UIEdgeInsetsZero
        print("ZERO")
    } else {
        myTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
    }

    myTableView.scrollIndicatorInsets = myTableView.contentInset
}

It works great for UITextField, but not for UITextView. Why?

+4
source share
1 answer

As Steve answered ( cancel keyboard using uiTextView )

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.delegate = self
    }

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if(text == "\n") {
            textView.resignFirstResponder()
            return false
        }
        return true
    }

}
+1
source

All Articles