Error Cannot convert value of type 'some View' to expected argument type 'Text'

111 Views Asked by At

I have a let txt = "Hello My name is jhon cena, call me +17878 Thank you" Now requirement is to make tappable phone number & make it bold font.

Here is my code which gives error Cannot convert value of type 'some View' to expected argument type 'Text'

struct CustomView1: View {
    let phoneNumber = "+17878"

    var body: some View {
        Text("Hello My name is Jhon Cena, call me ") +
        Text(phoneNumber)
            .font(.body)
            .fontWeight(.bold)
            .foregroundColor(.blue)
            .underline()
            .gesture(TapGesture().onEnded {
                self.dialNumber()
            })
        
        + Text(". Thank you")
            .font(.body)
    }

    func dialNumber() {
        // Replace this with the actual code to open the dialer with the provided phone number
        if let phoneURL = URL(string: "tel://\(phoneNumber)"), UIApplication.shared.canOpenURL(phoneURL) {
            UIApplication.shared.open(phoneURL)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        CustomView1()
    }
}
2

There are 2 best solutions below

0
Teja Nandamuri On

Check the order of modifiers you apply, and see the return type of those modifiers:

     Text(phoneNumber)
        .font(.body)        -> returns Text
        .fontWeight(.bold)  -> returns Text
        .foregroundColor(.blue) -> returns Text
        .underline() -> returns Text
        .gesture(TapGesture().onEnded { -> Doesn't return Text, it returns a View
            self.dialNumber()
        })

and you cannot basically append a View type and a Text type. If you want to perform an action with individual text elements, you need to put them in a HStack instead of adding them. It might be enough for two single line texts that won't wrap to second line.

More details can be found SwiftUI tappable subtext

0
TomaLambda On

If you're ok with your text being in a vstack what you can do is:

    var body: some View {
    VStack {
        Text("Hello My name is Jhon Cena, call me ")
        Text(phoneNumber)
            .font(.body)
            .fontWeight(.bold)
            .foregroundColor(.blue)
            .underline()
            .gesture(TapGesture().onEnded {
                self.dialNumber()
            })
        
        Text(". Thank you")
            .font(.body)
    }
}

Because you added gesture modifier to the phone number Text, it turns into a View. Another way is to put it into a HStack as a hacky solution.