简体   繁体   English

将文本视图退出为第一响应者,并在按下回车键时将文本字段设为第一响应者

[英]Resigning a text view as first responder and making a text field first responder when pressing return

I have an app with a text view and a text field where the user inputs a question in the view and an answer in the field.我有一个带有文本视图和文本字段的应用程序,用户在视图中输入问题并在字段中输入答案。 I want it to resign the view as first responder when the user presses return and make the field first responder and I tried the code below but it doesn't seem to be working and I can't figure out why我希望它在用户按下返回时将视图作为第一响应者退出并让该字段成为第一响应者,我尝试了下面的代码,但它似乎没有工作,我不知道为什么

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

I've tried the following code:我试过以下代码:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        guard text == "\n" else { return true }

        textView.resignFirstResponder()
        textField.becomeFirstResponder()

        return false
    }

It works as expected.它按预期工作。

I guess, the reason might be somewhere else.我想,原因可能在其他地方。 Do you have any more details to share?你有更多细节要分享吗?

Did you set text view's delegate?您是否设置了文本视图的委托? Do you stop at breakpoint inside shouldChangeTextIn method?您是否在shouldChangeTextIn方法内的断点处停止?

UPDATE:更新:

In comments it came clear that you conformed to the wrong protocol.在评论中很明显你遵守了错误的协议。 You need to conform to UITextViewDelegate instead of UITextFieldDelegate .您需要遵守UITextViewDelegate而不是UITextFieldDelegate You might want to keep UITextFieldDelegate conformance, if you need it for work with text field though.如果您需要它来处理文本字段,您可能希望保持UITextFieldDelegate一致性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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