Home > Back-end >  Event listeners on View element
Event listeners on View element

Time:12-14

In a SwiftUI View we can have a Button element, and this button element has onHover event as well as an event which fires on a button click (called action), like this:

Button("MyButton1", action: {
            // EVENT1: executed on button click
        })
            .onHover { hovered in
                // EVENT2: executed on hover event
            }

Now I have my own UI element which I defined like this:

struct MyCustomSwiftUIView: View {

var body: some View {
    HStack
    {
        Button("MyButton1", action: {
                // EVENT1: executed on button click
        })
            .onHover { hovered in
                // EVENT2: executed on hover event
            }
        }
    }
}

Now that I have MyCustomSwiftUIView defined, I want it to provide onClick and onHover events, just like the Button does. It should look like this:

MyCustomSwiftUIView()
    .onHover { hovered in
                // EVENT1: executed on hover event
            }
    .onClick {
                // EVENT2: executed on hover event
            }

The question: How can I add/implement these events on my own, custom made element MyCustomSwiftUIView?

PS: I am new to SwiftUI, and imho the language is pretty messed up. This is the first language I am not able to learn on my own, and I am struggling with basic concepts which are so different from any other language I have ever experienced. For the first time not even Google can help me (hope I am not being too dramatic).

CodePudding user response:

Rather than trying to use modifiers like .onHover and .onClick, I'd suggest you pass the closures as parameters. That would look like this:

struct ContentView : View {
    var body: some View {
        MyCustomSwiftUIView(
            onClick: {
                //click
            }, onHover: { hovered in
                //hover
            }
        )
    }
}

struct MyCustomSwiftUIView: View {
    var onClick : () -> Void
    var onHover : (Bool) -> Void
    
    var body: some View {
        HStack {
            Button("MyButton1", action: onClick)
                .onHover(perform: onHover)
        }
    }
}

Another example with built-in SwiftUI modifiers:

struct ContentView : View {
    var body: some View {
        MyCustomSwiftUIView()
            .onTapGesture {
                //click
            }
            .onHover { hovered in
                //hover
            }
    }
}

struct MyCustomSwiftUIView: View {
    var body: some View {
        HStack {
            Text("My custom view")
        }
    }
}
  • Related