Home > Software engineering >  How do I use a mailto link in Text() in swift 5, SwiftUI
How do I use a mailto link in Text() in swift 5, SwiftUI

Time:04-30

There are dozens of Stackoverflow answers for mailto links in Swift 5.

The consensus look like this

let url = NSURL(string: "mailto:[email protected]")
UIApplication.sharedApplication().openURL(url)

But how do I actually use this code? Ideally in an alert, but at least a general Text element

import SwiftUI

struct MainMenu: View {
    @State private var showAlert = false
    
    // What do I put here
    var emailLink:UIApplication {
        let url = URL(string: "mailto:[email protected]")!
        return UIApplication.shared.openURL(url)
    }
    
    // To make it work in here
    var body: some View {
        HStack(alignment: .center, spacing: .zero, content: {
            Text(
                "Here is an email link \(emailLink)"
            )
            
            Button(action: {
                showAlert = true
            }) {
                Text("MENU")
            }
            .alert(isPresented: $showAlert, content: {
                Alert(
                    title: Text("Title Here"),
                    message: Text(
                        "Need Help, \(emailLink)"
                    )
                )
            })
        })
    }
}

CodePudding user response:

You can use Environment var openURL for this, documentation alert

CodePudding user response:

Without an Alert, based on the suggestive comment of George this works:

var body: some View {
    Text(
        "Here is an email link "
    )
            
    Link("[email protected]", destination: URL(string: "mailto:[email protected]")!)
  • Related