为什么我的完成键没有退出键盘?

Why is my Done key not resigning the keyboard?

这可能是一个简单的问题,但我已经测试了很多不同的解决方案来解决这个测试项目中的一个问题,现在我在编辑我的 textView 字段时无法获得完成按钮来退出键盘.

我的代码应该在用户点击开始编辑时从键盘后面移动 textView。然后,完成后,用户应该能够点击完成键并隐藏键盘并将 textView 移回视图底部。在此代码中,点击屏幕将使键盘退出并将 textView 移至其原始位置。问题是,当我在编辑 textView 时点击完成时,它会插入一个回车符 return。

似乎我在 SO 中看到她的所有其他问题都是针对 Objective-C 的。我正在使用Swift 2.谢谢你的帮助。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {

@IBOutlet var textViewField: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    textViewField.layer.cornerRadius = 10
}

func textViewDidBeginEditing(textView: UITextView) { // became first responder

    //move textView up
    let myScreenRect: CGRect = UIScreen.mainScreen().bounds
    let keyboardHeight : CGFloat = 250

    UIView.beginAnimations( "animateView", context: nil)
    //var movementDuration:NSTimeInterval = 0.35
    var needToMove: CGFloat = 0

    var frame : CGRect = self.view.frame
    if (textView.frame.origin.y + textView.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight)) {
        needToMove = (textView.frame.origin.y + textView.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight);
    }

    frame.origin.y = -needToMove
    self.view.frame = frame
    UIView.commitAnimations()
}

func textViewDidEndEditing(textView: UITextView) {
    //move textfields back down
    UIView.beginAnimations( "animateView", context: nil)
    var frame : CGRect = self.view.frame
    frame.origin.y = 0
    self.view.frame = frame
    UIView.commitAnimations()
}

//function to hide keyboard when Done key tapped for textField
func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

//funtion to hide keyboard when screen is tapped
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.view.endEditing(true)
}

}

在 viewDidLoad 中将 VC 指定为文本视图委托并使用 'shouldChangeTextInRange' 文本视图委托

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
    textViewField.layer.cornerRadius = 10
}

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