How to create tappable url/phone number in SwiftUI

前端 未结 6 1310
Happy的楠姐
Happy的楠姐 2021-01-04 10:06

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\'.

Is there a way to do this with

相关标签:
6条回答
  • 2021-01-04 10:39

    Make it a Button() with an action, not a Text() with a gesture.

    0 讨论(0)
  • 2021-01-04 10:44

    Try this,

    let strNumber = "123-456-7890"
    
    Button(action: {
        let tel = "tel://"
        let formattedString = tel + strNumber 
        guard let url = URL(string: formattedString) else { return }
        UIApplication.shared.open(url) 
       }) {
       Text("123-456-7890")
    }
    
    0 讨论(0)
  • 2021-01-04 10:46

    From iOS 14, Apple provides us a Link view by default. So, you can just use this,

    Link("Anyone can learn Swift", destination: URL(string: "https://ohmyswift.com")!)
    

    For the previous versions of iOS, like iOS 13.0, you still have to use

    Button("Anyone can learn Swift") {
       UIApplication.shared.open(URL(string: "https://ohmyswift.com")!)
    }
     
    
    0 讨论(0)
  • 2021-01-04 10:49

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

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

    UIApplication.shared.open(url)
    

    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:

    How to use openURL for making a phone call in Swift?

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

    The full code of what worked is

    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!)
    }
    
    0 讨论(0)
  • 2021-01-04 11:01

    Using iOS 14 / Xcode 12.0 beta 5

    Use new link feature in SwiftUI for phone and email links.

        // Link that will open Safari on iOS devices
        Link("Apple", destination: URL(string: "https://www.apple.com")!)
        
        //  Clickable telphone number
        Link("(800)555-1212", destination: URL(string: "tel:8005551212")!)
    
        //  Clickable Email Address
        Link("apple@me.com", destination: URL(string: "mailto:apple@me.com")!)
        
    
    0 讨论(0)
  • 2021-01-04 11:02

    KISS answer:

    Button("url") {UIApplication.shared.open(URL(string: "https://google.com")!)}
    
    0 讨论(0)
提交回复
热议问题