【问题标题】:Swift - React on "@" when pressing the keyboardSwift - 按下键盘时对“@”做出反应
【发布时间】:2021-09-10 14:46:52
【问题描述】:

每当用户点击键盘上的“@”字符时,我都想调用一个函数。

目前,我正在使用以下方法

func textViewDidChange(_ textView: UITextView) { //Handle the text changes here
   if (textView.text.contains("@") {
      doSomething()
   }
}

但是,上面的代码对我不起作用,因为我的文本视图将包含像 @ 这样的字符。这意味着,在我的文本视图中至少有一次 @ 之后,每次我在键盘上键入内容时,它都会调用 doSomething() 函数。还有其他方法可以检查用户的输入吗?

【问题讨论】:

  • 改为检查textField(_:shouldChangeCharactersIn:replacementString:)。检查replacementString?并检查您是否已经doingSomething(),以防万一?

标签: swift xcode textview keyboard mention


【解决方案1】:

而不是检查 textViewDidChange 移动到 shouldChangeCharactersIn

func textField(_ textView: UITextView, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if (textView.text.contains"@") { // Already have @ value
        doSomething()
    }
    if (string == "@") { // user input char
        doSomething()
    }
    return true
}

参考 => https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618630-textview

【讨论】:

    猜你喜欢
    • 2015-05-17
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多