在IB的库中,介绍告诉我们,当按下返回键时,UITextView的键盘将消失。但实际上返回键只能作为'\n'

我可以添加一个按钮,并使用[txtView resignFirstResponder]隐藏键盘。

但是有没有办法为键盘中的返回键添加动作,这样我就不需要添加UIButton了?


当前回答

问题问的是如何用返回键来做,但我认为这可以帮助那些想要在使用UITextView时让键盘消失的人:

private func addToolBarForTextView() {
    let textViewToolbar: UIToolbar = UIToolbar()
    textViewToolbar.barStyle = .default
    textViewToolbar.items = [
        UIBarButtonItem(title: "Cancel", style: .done,
                  target: self, action: #selector(cancelInput)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                  target: self, action: nil),
        UIBarButtonItem(title: "Post Reply", style: .done,
                  target: self, action: #selector(doneInput))
    ]
    textViewToolbar.sizeToFit()
    yourTextView.inputAccessoryView = textViewToolbar
}

@objc func cancelInput() { print("cancel") }
@objc func doneInput() { print("done") }

override func viewDidLoad() {
    super.viewDidLoad()
    addToolBarForTextView()
}

在viewDidLoad或其他生命周期方法中调用addToolBarForTextView()。

这对我来说似乎是一个完美的解决方案。

欢呼,

穆拉特

其他回答

不要忘记为textView设置委托-否则resignfirstresponder将无法工作。

在视图控制器中添加这个方法。

迅速:

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

这个方法对你也有帮助:

/**
Dismiss keyboard when tapped outside the keyboard or textView

:param: touches the touches
:param: event   the related event
*/
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        if touch.phase == UITouchPhase.Began {
            textField?.resignFirstResponder()
        }
    }
}

UITextView没有任何在用户点击返回键时被调用的方法。如果您希望用户只能添加一行文本,请使用UITextField。按回车键并隐藏UITextView的键盘不符合接口准则。

即使这样,如果你想这样做,实现textView:shouldChangeTextInRange:replacementText:方法的UITextViewDelegate,并在检查替换文本是否\n,隐藏键盘。

也许还有别的办法,但我不知道有什么办法。

银行的国际代码

在你的类/视图中实现UITextViewDelegate,如下所示:

class MyClass: UITextViewDelegate  { ...

设置textView委托为self

myTextView.delegate = self

然后实现以下内容:

  func textViewDidChange(_ textView: UITextView) {
    if textView.text.characters.count >= 1 {

        if let lastChar = textView.text.characters.last {

            if(lastChar == "\n"){

              textView.text = textView.text.substring(to: textView.text.index(before: textView.text.endIndex))
              textView.resignFirstResponder()
            }
        }
    }
}

编辑 我更新了代码,因为它从来都不是一个好主意,改变用户在文本框的输入,以解决问题,而不是在黑客代码完成后重新设置状态。

对于Xcode 6.4。Swift 1.2。:

   override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
    {
        super.touchesBegan(touches, withEvent: event)
        if let touch = touches.first as? UITouch
        {
            self.meaningTextview.resignFirstResponder()
        }
    }