欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS 检测文本中的URL、电话号码等信息

程序员文章站 2023-12-20 12:38:16
要检测文本中的 url、电话号码等,除了用正则表达式,还可以用 nsdatadetector。 用 nstextcheckingresult.checkingty...

要检测文本中的 url、电话号码等,除了用正则表达式,还可以用 nsdatadetector。

  1. 用 nstextcheckingresult.checkingtype 初始化 nsdatadetector
  2. 调用 nsdatadetector 的 matches(in:options:range:) 方法获得 nstextcheckingresult 数组
  3. 遍历 nstextcheckingresult 数组,根据类型获取相应的检测结果,通过 range 获取结果文本在原文本中的位置范围(nsrange)

下面的例子是把 nsmutableattributedstring 中的 url、电话号码突出显示。

func showattributedstringlink(_ attributedstr: nsmutableattributedstring) {
  // we check url and phone number
  let types: uint64 = nstextcheckingresult.checkingtype.link.rawvalue | nstextcheckingresult.checkingtype.phonenumber.rawvalue
  // get nsdatadetector
  guard let detector: nsdatadetector = try? nsdatadetector(types: types) else { return }
  // get nstextcheckingresult array
  let matches: [nstextcheckingresult] = detector.matches(in: attributedstr.string, options: nsregularexpression.matchingoptions(rawvalue: 0), range: nsrange(location: 0, length: attributedstr.length))
  // go through and check result
  for match in matches {
    if match.resulttype == .link, let url = match.url {
      // get url
      attributedstr.addattributes([ nslinkattributename : url,
                     nsforegroundcolorattributename : uicolor.blue,
                     nsunderlinestyleattributename : nsunderlinestyle.stylesingle.rawvalue ],
                    range: match.range)
    } else if match.resulttype == .phonenumber, let phonenumber = match.phonenumber {
      // get phone number
      attributedstr.addattributes([ nslinkattributename : phonenumber,
                     nsforegroundcolorattributename : uicolor.blue,
                     nsunderlinestyleattributename : nsunderlinestyle.stylesingle.rawvalue ],
                    range: match.range)
    }
  }
}

用于初始化 nsdatadetector 的参数 types 的类型是 nstextcheckingtypes,实际上是 uint64。可以用或运算符连接多个值,以实现同时检测多种类型的文本。

public typealias nstextcheckingtypes = uint64

nstextcheckingresult 的检测结果属性与类型有关。例如,当检测类型是 url (resulttype == .link),就可以通过 url 属性获取检测到的 url。

给 nsmutableattributedstring 添加下划线,nsunderlinestyleattributename 作为 key 对应的值在 swift 中可以为 int,不能为 nsunderlinestyle。所以要写nsunderlinestyle.stylesingle.rawvalue。写nsunderlinestyle.stylesingle会导致 nsmutableattributedstring 显示不出来。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!

上一篇:

下一篇: