如何在 SwiftUI 中创建可点击的 url/电话号码 [英] How to create tappable url/phone number in SwiftUI

查看:40
本文介绍了如何在 SwiftUI 中创建可点击的 url/电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 SwiftUI 文本(或任何视图)中显示电话号码,然后使其可点击,以便打开电话".

I would like to display a phone number in a SwiftUI Text (or any View), and then make it clickable so that it will open the 'Phone'.

有没有办法用 SwiftUI 来做到这一点,或者我应该尝试在 SwiftUI 中包装一个 UITextView 并用 NSAttributed 字符串等老式方法来做?

Is there a way to do this with SwiftUI, or should I try to wrap a UITextView in SwiftUI and do it the old-fashioned way with NSAttributed string etc?

我已阅读 SwiftUI 中的 Text 文档,但找不到任何有关如何执行此操作的信息.目前正在 Xcode 11 beta 5 中尝试这样做.

I've read the documentation for Text in SwiftUI, and couldn't find anything about how to do this. Currently trying to do this in Xcode 11 beta 5.

我在 SwiftUI.h 中的 SwiftUI API 中搜索了文本"

I've searched 'text' in the SwiftUI API in SwiftUI.h

我还搜索过 stackoverflow [swiftui] 和 google,其中包含使电话号码/网址可点击"、可点击链接/网址 swiftUI"等查询.

I've also searched stackoverflow [swiftui] and google with queries like "make phone number/url tappable", "Tappable link/url swiftUI" etc..

Text("123-456-7890")
    .onTapGesture {
    // do something here
}

(文字为日本电话号码)

(text will be Japanese phone number)

推荐答案

感谢 Ashish 的回答,我找到了解决此问题所需的必要代码:

Thanks to Ashish's answer, I found the necessary code I needed to solve this:

在按钮的 inside 操作中 - 您需要调用此方法:

In the action inside of the Button - you need to call this method:

UIApplication.shared.open(url)

实际拨打电话/在 SwiftUI 视图中打开链接.

to actually make the phone call / open a link in a SwiftUI View.

当然,一开始我不明白如何格式化我的电话号码,我在这些答案中找到了:

Of course, I didn't understand how to format my phone number at first, which I found in these answers:

如何使用 openURL 制作一个用 Swift 打电话?

不要忘记将tel://"添加到字符串的开头/将其格式化为 URL..

Don't forget to add the 'tel://' to the beginning of your string/format it as URL..

工作的完整代码是

Button(action: {

    // validation of phone number not included
    let dash = CharacterSet(charactersIn: "-")

    let cleanString =     
    hotel.phoneNumber!.trimmingCharacters(in: dash)

    let tel = "tel://"
    var formattedString = tel + cleanString
    let url: NSURL = URL(string: formattedString)! as NSURL

    UIApplication.shared.open(url as URL)

}) {
Text(verbatim: hotel.phoneNumber!)
}

这篇关于如何在 SwiftUI 中创建可点击的 url/电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆