代码之家  ›  专栏  ›  技术社区  ›  Dani iman kazemayni

检测UITextField中的引用不起作用

  •  0
  • Dani iman kazemayni  · 技术社区  · 7 年前

    @ )在一个 UITextField . 基本上,我要做的是转换文本 String 用户输入到 array 然后在每个项目中循环查看是否有 前缀。出于某种原因,尽管我在提到的周围输入了较长的文本(或仅提到),但它显示了1个空字符串项。我显然做错了什么,但我不知道是什么

    if let mentionsArray = self.commentTextField.text?.components(separatedBy:  CharacterSet.whitespacesAndNewlines) {
    
           for  mention in mentionsArray  {
               if mention.hasPrefix("@")  {
                    print(mention)
               }
           }
     }
    

    值得一提的是,这段代码是在闭包中运行的。

    代码实际上是有效的,但是下面的评论询问了 commentTextField.text 它让我意识到,在达到这一点之前,我清空了文本字段的内容。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Rakesha Shastri    7 年前

    你的 commentTextField 可能是 空的 components(separatedBy: CharacterSet.whitespacesAndNewlines) 将返回空字符串。

        2
  •  2
  •   Jaydeep Vora    7 年前

    下面是我用来从字符串中检测心理状态文本的扩展名。

    extension String {
            func findMentionText() -> [String] {
                var arr_hasStrings:[String] = []
                let regex = try? NSRegularExpression(pattern: "(@[a-zA-Z0-9_\\p{Arabic}\\p{N}]*)", options: [])
                if let matches = regex?.matches(in: self, options:[], range:NSMakeRange(0, self.count)) {
                    for match in matches {
                        arr_hasStrings.append(NSString(string: self).substring(with: NSRange(location:match.range.location, length: match.range.length )))
                    }
                }
                return arr_hasStrings
            }
        }