【问题标题】:call a method with the "Return" (Done) Button of the keyboard使用键盘的“返回”(完成)按钮调用方法
【发布时间】:2011-07-09 18:25:08
【问题描述】:

有没有人可以给我一个示例方法,通过按下键盘的返回按钮调用并将 textview 的文本(之前输入的)保存在 nsuserdefaults 中?

非常感谢:)

【问题讨论】:

    标签: objective-c ios4 keyboard return nsuserdefaults


    【解决方案1】:

    确保您的UITextField 的返回键类型设置为UIReturnKeyGo(这是用于键盘上的图像):

    theTextField.returnKeyType = UIReturnKeyGo;
    

    然后用这个方法做任何你想做的事:

    - (BOOL) textFieldShouldReturn:(UITextField *)textField
    {
        // Tell the keyboard where to go on next / go button.
        if(textField == theTextField)
        {
            // do stuff
        }
    
        return YES;
    }
    

    要从文本字段中获取文本,只需调用 theTextField.text 并根据需要保存!

    斯威夫特版

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // Tell the keyboard where to go on next / go button.
        if textField == theTextField {
            // do stuff
        }
    
        return true
    }
    

    【讨论】:

    • 为什么我们需要在这个方法中使用if 语句?是否要检查同一个视图控制器中的多个文本字段?
    • 如果您有多个文本字段,例如,您可能希望只提交最后一个。
    • 请记住,您需要更改键盘样式以匹配此内容。
    • 这篇文章还帮助解释了有关代表的更多信息:stackoverflow.com/questions/6190276/…
    • 不要忘记将您的控制器连接为UITextField 的代表并实现UITextFieldDelegate
    【解决方案2】:

    如果你是动态添加 UITextField 到一个 UITableCell,你还需要为它设置委托:

        self.textfield.delegate = self;
    

    你还需要在头文件中添加这个:

        @interface YourController: UIViewController <UITextFieldDelegate>
    

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多