iOS 檢測文本中的URL、電話號碼等信息
要檢測文本中的 URL、電話號碼等,除了用正則表達式,還可以用 NSDataDetector。
- 用 NSTextCheckingResult.CheckingType 初始化 NSDataDetector
- 調用 NSDataDetector 的 matches(in:options:range:) 方法獲得 NSTextCheckingResult 數(shù)組
- 遍歷 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 顯示不出來。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關文章
iOS App開發(fā)中的UISegmentedControl分段組件用法總結
UISegmentedControl主要被用來制作分頁按鈕或添加跳轉到不同位置的標簽,這里我們就來看一下iOS App開發(fā)中的UISegmentedControl分段組件用法總結,需要的朋友可以參考下2016-06-06
iOS實現(xiàn)實時檢測網(wǎng)絡狀態(tài)的示例代碼
網(wǎng)絡連接狀態(tài)檢測對于我們的iOS開發(fā)來說是一個非常通用的需求。下面這篇文章主要就給大家介紹了關于利用iOS實現(xiàn)實時檢測網(wǎng)絡狀態(tài)的相關資料,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-07-07
iOS使用UIScrollView實現(xiàn)無限循環(huán)輪播圖效果
這篇文章主要介紹了iOS使用UIScrollView實現(xiàn)無限循環(huán)輪播圖效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
iOS如何去掉導航欄(UINavigationBar)下方的橫線
本篇文章主要介紹了iOS如何去掉導航欄(UINavigationBar)下方的橫線,非常具有實用價值,需要的朋友可以參考下2017-05-05

