'Passing tap action between views in swiftUI

I'm a beginner in swiftui and I'm trying to build attributed type text in swiftui. I was able to do so, now for the link instead of url I need to have a custom popup so I'm trying to pass the tap action from the text to my main view but it's not working, below is my code.

    struct ContentText: View {
        private var splitText: [String]
        let count: Int
        var type: ViewType
        @State var handler: ((String) -> Void) = {_ in}
    
        init(_ text: String, type: ViewType = .text) {
            self.splitText = text.split(separator: " ").map { "\($0) " }
            if text.hasPrefix(" ") {
                self.splitText = [" "] + self.splitText
        }
        self.type = type
        self.count = splitText.count
    }

    var body: some View {
        ForEach(self.splitText.indices, id:\.self) { index in
            switch type {
            case .bold:
                Text(splitText[index]).fontWeight(.bold)
            case .link:
                Text(splitText[index]).fontWeight(.bold).foregroundColor(.blue).onTapGesture {
                   //need to pass this action                    
                    handler(splitText[index])
                }
            default:
                Text(splitText[index])
            }
        }
    }
}

struct TextHyperLinkView: View {
    var content: [ContentText] = [
        ContentText("By completing the form by choosing "),
        ContentText("Accept, ", type: .bold),
        ContentText("I consent to give …"),
        ContentText("Privacy policy", type: .link)]
    
    @State var handler: ((String) -> Void)

    @State private var height: CGFloat = 0

    var body: some View {
        VStack {
            GeometryReader { geometry in
                ZStack(alignment: .topLeading) {
                    self.zStackViews(geometry)
                }
                .background(calculateHeight($height))
            }
        }.frame(height: height)
            .onAppear {
                guard let linkContent = content.filter({ $0.type == .button }).first else { return }
                //Need Pass handler action here
                handler = linkContent.handler
            }
    }
 //other functions

}

// This is my main view
struct PolicyView: View {
    
    var body: some View {
        VStack(spacing: 10){
            Text("Disclaimer").frame( maxWidth: .infinity, alignment: .leading).font(.system(size: 14))
            TextHyperLinkView { value in
                //DOESNT GET CALLED
                print("handler called \(value)")
            }
            
        }.padding()
    }
}

Any help is appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source