Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFTUI - How to create an image linked to an URL?

I would like to insert an URL to an image, I feel like it should be very simple but I couldn't make it work.

Button(action: {}) {
 Image("london").resizable().frame(width: 350.0, height: 233.0).buttonStyle(PlainButtonStyle())
            }

I want to go to "https://www.google.com" when the button is tapped.

like image 351
I Kaya Avatar asked Oct 14 '25 23:10

I Kaya


2 Answers

To open a url in a browser on the phone, you need to first construct the URL, then you have to check that the application can actually open it and only then you can ask the application to open the url for you.

 Button(action: {
     guard let google = URL(string: "https://www.google.com/"),
         UIApplication.shared.canOpenURL(google) else {
         return
     }
     UIApplication.shared.open(google,
                               options: [:],
                               completionHandler: nil)
 }) {
    Image(systemName: "magnifyingglass")
        .resizable()
        .frame(width: 250.0,
               height: 233.0)
        .buttonStyle(PlainButtonStyle())
    }
like image 70
LuLuGaGa Avatar answered Oct 17 '25 12:10

LuLuGaGa


Use UIApplication.shared.open(url, options: [:], completionHandler: nil) at action for the button.

like image 33
HansDeBeer Avatar answered Oct 17 '25 13:10

HansDeBeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!