使用 NSDataDetector 就像 Apple 的 Notes 应用程序一样

Using NSDataDetector to just like Apple's Notes app

我正在尝试查找几种不同的数据类型,包括日期、地址、Phone 数字和链接。我已经能够找到它们,但我希望能够通过下划线和更改颜色来格式化它们。到目前为止,这是我的代码。

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 {

我在想我应该先把每个结果都从循环中取出然后 1)将它们变成字符串 2)格式化它们。

第一个问题。我如何将我的格式化字符串放回到我的 UITextView 的同一个地方?

第二个问题。我正在考虑像这样创建一个开关

switch match {
                case match == NSTextCheckingType.date

但是现在我有了特定类型的 NSTextCheckingType,我需要做什么才能使它们具有我想要的功能? (例如,拨打 phone 号码、打开地址地图、为日期创建活动)

要执行 Notes 的操作,您只需在文本视图上设置 dataDetectorTypes 属性。就这样!不涉及 NSDataDetector。