国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > iOS > 正文

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

2019-10-21 18:47:10
字體:
來源:轉載
供稿:網(wǎng)友

要檢測文本中的 URL、電話號碼等,除了用正則表達式,還可以用 NSDataDetector。

  1. 用 NSTextCheckingResult.CheckingType 初始化 NSDataDetector
  2. 調用 NSDataDetector 的 matches(in:options:range:) 方法獲得 NSTextCheckingResult 數(shù)組
  3. 遍歷 NSTextCheckingResult 數(shù)組,根據(jù)類型獲取相應的檢測結果,通過 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 的參數(shù) types 的類型是 NSTextCheckingTypes,實際上是 UInt64。可以用或運算符連接多個值,以實現(xiàn)同時檢測多種類型的文本。

public typealias NSTextCheckingTypes = UInt64

NSTextCheckingResult 的檢測結果屬性與類型有關。例如,當檢測類型是 URL (resultType == .link),就可以通過 url 屬性獲取檢測到的 URL。

給 NSMutableAttributedString 添加下劃線,NSUnderlineStyleAttributeName 作為 key 對應的值在 Swift 中可以為 Int,不能為 NSUnderlineStyle。所以要寫NSUnderlineStyle.styleSingle.rawValue。寫NSUnderlineStyle.styleSingle會導致 NSMutableAttributedString 顯示不出來。

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持VEVB武林網(wǎng)!


注:相關教程知識閱讀請移步到IOS開發(fā)頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 襄樊市| 昌都县| 辉南县| 牡丹江市| 依安县| 文安县| 原平市| 凤山县| 陆河县| 神农架林区| 乐陵市| 镇宁| 镇原县| 穆棱市| 蓬溪县| 三原县| 隆子县| 荃湾区| 青田县| 吕梁市| 新泰市| 太湖县| 洪雅县| 永泰县| 洱源县| 福建省| 榆中县| 湘西| 襄垣县| 怀化市| 烟台市| 汉源县| 英山县| 南江县| 东海县| 宝坻区| 平乐县| 梁山县| 惠水县| 宁河县| 宁南县|