当在 UITextView 上输入时按下 return 按钮时,有没有办法触发一个函数?
Is there a way to trigger a function when the return button has been pressed when typing on UITextView?
当我使用 UITextField
而不是 UITextView
时,我可以将协议 UITextFieldDelegate
添加到工作 class 并遵守协议并添加如下功能:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
handleSend()
return true
}
按下键盘上的 return 按钮会触发函数 handleSend()
。
有一个名为 UITextViewDelegate
的协议,但没有名为 textViewShouldReturn
的函数。
如何使用 UITextView
实现此目的?
你可以试试:
Swift 4:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
handleSend()
}
return true
}
Swift 3:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
handleSend()
}
return true
}
当我使用 UITextField
而不是 UITextView
时,我可以将协议 UITextFieldDelegate
添加到工作 class 并遵守协议并添加如下功能:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
handleSend()
return true
}
按下键盘上的 return 按钮会触发函数 handleSend()
。
有一个名为 UITextViewDelegate
的协议,但没有名为 textViewShouldReturn
的函数。
如何使用 UITextView
实现此目的?
你可以试试:
Swift 4:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
handleSend()
}
return true
}
Swift 3:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
handleSend()
}
return true
}