键盘隐藏UITextView swift 2

4
我正在使用带有2个自定义单元格的UITableView,其中我有使用UITextViewUITextField的自定义单元格,在键盘将编辑的字段隐藏在其上方时,我尝试将其移动到键盘顶部。这是我的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)

    }

这里是当键盘通知被发送时调用的函数:

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
}

对于UITextField,它可以完美地工作,但是对于UITextView却不能。为什么呢?

1个回答

1

正如Steve所回答的那样(使用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
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接