iosswiftnsdatadetector

Using NSDataDetector to just like Apple's Notes app


I'm trying to find several different data types including Dates, Addresses, Phone numbers, and Links. I'm already able to find them but I want to be able to format them by underlining and changing their color. This is my code so far.

func detectData() {
        let text = self.textView.text
        let types: NSTextCheckingType = .Date | .Address | .PhoneNumber | .Link
        var error: NSError?
        let detector = NSDataDetector(types: types.rawValue, error: &error)
        var dataMatches: NSArray = [detector!.matchesInString(text, options: nil, range: NSMakeRange(0, (text as NSString).length))]

        for match in dataMatches {

I was thinking I should first get each result out of the loop then 1) turn them into strings 2)format them.

First question. How will I put my formatted string back into my UITextView at the same place?

Second question. I'm thinking about creating a switch like so

switch match {
                case match == NSTextCheckingType.date

but now that I have a specific type of NSTextCheckingType, what do I have to do to make them have the functionality I want? (e.g. call a phone number, open up maps for an address, create a event for a date)


Solution

  • To do what Notes does you just need to set the dataDetectorTypes property on your text view. That's all! No NSDataDetector involved.