-3

I'm currently building an app which has a series of views. When a user clicks on one of these views, I want it to perform an action via a function.

How do I allow this view to complete a function?

I can't create an outlet for it where I can call a function inside the body like with a button.

I'm very new to Swift so there may be something I'm missing, but there doesn't seem to be anything obvious having had a Google and read around.

To hopefully demonstrate my point, the below image is a given view.

enter image description here

When the user clicks on this view, I want them to be taken to a URL where they can send a message.

I think I've got the URL part, I just need to be able to call the function in question when that View gets pressed on.

Jon Nicholson
  • 927
  • 1
  • 8
  • 29

3 Answers3

1

You can add Tap Gestures to the view. With gesture recognizer you can easily do the job. For details of tap gestures you can visit below link - https://developer.apple.com/documentation/uikit/touches_presses_and_gestures/handling_uikit_gestures/handling_tap_gestures

1

You can attach a gesture to the view. There is an onTapGesture

    Text("Tappable Text View")
        .onTapGesture { functionToCall() }

There is an alternative way:

    Text("Tappable Text View")
        .gesture(TapGesture().onEnded { _ in
            functionToCall()
            }
        )

This second approach lets you specify modifiers which is less of an issue for iOS, but are needed for macOS if you want to support things Mac users expect. For example, option-clicking:

    Text("Tappable Text View")
        .gesture(TapGesture().modifiers([.option]).onEnded
            { _ in
                functionToCall()
            }
        )
Chip Jarred
  • 2,600
  • 7
  • 12
0

if you are using swiftui you can use onTapGesture but this is already told. Making button is one other way.

Button(action{//call your url here
  },Label{
   //build your button ui here 
  })