如何拦截 UITextView 中链接上的电话号码点击(通话按钮)?

Man*_*sha 3 uitextview datadetectortypes uitextviewdelegate ios swift

当我们单击文本视图中的数字时,是否有回调来识别用户何时单击弹出窗口中的“呼叫”

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool

上面提到的函数将帮助我识别 UITextView 中的链接已被单击,而是否有一个特定的回调来识别是否单击了“调用”或单击了“取消”

Azi*_*ziz 5

使用委托方法:

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
        print("Phone \(URL)")
        return false
}
Run Code Online (Sandbox Code Playgroud)

不要忘记连接 textView 委托。

self.textView.delegate = self
Run Code Online (Sandbox Code Playgroud)

然后你可以添加一个自定义的UIAlertController来调用或取消。

编辑:

这是完整的代码:

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {

    if (URL.scheme == "tel"){
        let phoneNumber = URL.absoluteString.stringByReplacingOccurrencesOfString("tel:", withString: "")
        let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "Call", style: .Default, handler: { (alert) in
            if UIApplication.sharedApplication().canOpenURL(URL) {
                UIApplication.sharedApplication().openURL(URL)
            }
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (alert) in
            print("User Canceld")
        }))
        presentViewController(alert, animated: true, completion: nil)
        return false
    }

    return true
}
Run Code Online (Sandbox Code Playgroud)

最后一件事,在您的 info.plist 中添加:

<key>LSApplicationQueriesSchemes</key>
<array>
<string>tel</string>
</array>
Run Code Online (Sandbox Code Playgroud)