How to Create a Tappable Link in Text in SwiftUI

If you want to add a link to a Text in SwiftUI, you'll need to call the .onTapGesture modifier as well as UIApplication.shared.open.

Open a web page in Safari when the user clicks on a link in your SwiftUI application

 

Single link

For example, if the user clicks on the following text, we want to lead them to the Design+Code website. So we'll do something like this:

Text("Visit Swift UI IO")
		.onTapGesture {
				UIApplication.shared.open(URL(string: "https://www.swiftuiio.com/")!, options: [:])
		}

..

Multiple links 

If you have a long text with multiple links, just wrap them in a HStack:

HStack {
		Text("You agree to our")

		Text("Terms")
				.onTapGesture {
						 UIApplication.shared.open(URL(string: "https://www.swiftuiio.com/2022/08/privacy-policy.html")!)
				}

		Text("and")

		Text("Privacy policy")
				.onTapGesture {
						 UIApplication.shared.open(URL(string: "https://www.swiftuiio.com/2022/08/privacy-policy.html")!)
				}

		Text(".")
}

..

Comments