How to create tappable url/phone number in SwiftUI

前端 未结 6 1347
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: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!)
    }
    

提交回复
热议问题