简体   繁体   中英

Keyboard hide UITextView swift 2

I m using UITableView with 2 customs cells, I have custom cells with UITextView and UITextField , I'm trying to move up the edited field when it's hiding by the keyboard on the top of the keyboard, here is my code for the 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 the function called when 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's working perfectly for the UITextField but not for the UITextView . Why?

As answered by Steve ( dismiss keyboard with a 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
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM