溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

iOS 檢測文本中的URL、電話號碼等信息

發布時間:2020-10-25 05:18:20 來源:腳本之家 閱讀:239 作者:Silence_cnblogs 欄目:移動開發

要檢測文本中的 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 顯示不出來。

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持億速云!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女