UITextView's Data Detectors options and text apperance

1.4k views Asked by At

UITextView provides a very useful Data Detectors functionality, that supports:

  • Phone number detection
  • URL detection Street address detection
  • Event detection
  • Shipment tracking number detection
  • Flight number detection, and
  • Information users may want to look up

I prepared a small sample to test it out, and I just have one question:

How can I change the appearance of detected text?

Changes applied to tintColor and/or linkTextAttributes appears to only work for URL, email, and phone number. Changes applied to tintColor or linkTextAttributes properties of UITextView DOES NOT appear to have any effect on items like Event/ Date or Time, Address, Shipment Number, and Flight Number.

UITextView's Data Detectors option sample

1

There are 1 answers

0
Satachito On

There seems to be only one way using NSDataDetector.

Sample of the date detection is below.

let wAS = aTextView.attributedText.mutableCopy() as! NSMutableAttributedString

let wDateResult = try! NSDataDetector( types: NSTextCheckingResult.CheckingType.date.rawValue ).matches(
    in: wAS.string
,   options: NSRegularExpression.MatchingOptions( rawValue: 0 )
,   range: NSMakeRange( 0, wAS.string.characters.count )
)
for w in wDateResult {
    wAS.addAttributes( [ NSForegroundColorAttributeName : UIColor.red ], range: w.range )
}

aTextView.attributedText = wAS