iOS:处理文本 field/view 交互和键盘移动的最稳定方式?

iOS: Most stable way to handle text field/view interactions and keyboard movements?

我有一个混合了文本字段和文本视图的应用程序,人们可以通过各种方式与它们进行交互。有些从输入字段切换到输入字段,有些输入字段并点击 "done," 等

有没有人找到一种他们特别喜欢处理 fields/views 之间切换的方法,同时根据输入的数据更新内部数据模型?有什么喜欢的技巧吗?

相关:如果有人从一个字段切换到另一个字段,每个字段的委托调用顺序是什么(should/did begin/end 编辑),以及 resignFirstResponder() 如何发挥作用?

谢谢!

您可以为每个 UITextField 和 UITextView 设置唯一的标签,以便为每个 UITextField 或 UITextView 相应地区分和存储数据。每当有人与 UITextField 交互时,都可以使用以下委托方法

func textViewDidBeginEditing(textView: UITextView)
func textFieldDidBeginEditing(textView: UITextField)

每当我们开始编辑 UITextField 或 UITextView 时,都会调用上述两个委托函数。这些功能可用于相应地调整您的布局,以便您的 UITextField 或 UITextView 不会落后于键盘。但是,如果视图中有多个 UITextField 和 UITextView,最好使用第三方库来完成此任务。我在我的一个项目中使用了这个 https://github.com/michaeltyson/TPKeyboardAvoiding

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 

利用以上两个函数,可以跟踪UITextField和UITextView内部文本的变化

func textViewDidEndEditing(textView: UITextView)
func textFieldDidEndEditing(textField: UITextField)

只要在特定的 UITextView 或 UITextField 中结束编辑,就会调用以上两个函数。这可用于根据标签存储来自 UITextField 或 UItextView 的数据。

func textFieldShouldReturn(textField: UITextField) -> Bool 

点击return键时调用。您还可以使用它根据标签等将在此文本字段中键入的文本存储在数组中