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

2025-05-29 0 19

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

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

下面的例子是把 NSMutableAttributedString 中的 URL电话号码突出显示。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
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 显示不出来。

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS 检测文本中的URL、电话号码等信息 https://www.kuaiidc.com/90656.html

相关文章

发表评论
暂无评论