'Dynamically Combining Currency Symbol to TextField Text

Is it possible to dynamically combine a currency symbol to some text before displaying it via TextField on a single text line? Currently my currency symbol is on the line above the TextField text "Enter Amount > "

This code produces the errors: "Cannot assign to property: 'self' is immutable" and "Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols."

I would like to use something like this in a form.

struct ContentView: View {
    
    @State private var moneyS: String = ""
    var curr: String = ""
    var curSymb: Int = 2
    var mxx: String = ""
    
    
    var body: some View {

        Text("Blah Blah Blah")
        
        switch curSymb {
        
        case 1:
            curr = "$"
            
        case 2:
            curr = "€"
            
        default:
            curr = "£"
            
        }
        
        mxx = "Enter Amount > " + curr
        
        
        
        TextField(mxx, text: $moneyS)
        .keyboardType(.decimalPad)

    }
}


Solution 1:[1]

Yes, it certainly is possible. By default, it uses VStack-like layout and places all the views vertically. We can use HStack (horizontal stack) to align your text views horizontally.

Here is the updated version:

struct ContentView: View {
    
   ...
    
    var curr: String {
        switch curSymb {
        case 1: return "$"
        case 2: return "€"
        default: return "£"
        }
    }
    
    var body: some View {
        HStack(alignment: .firstTextBaseline) { // note that we use firstTextBaseline in order to keep the text aligned even if you decided to have different font for every part of the text
            Text("Blah Blah Blah")
            TextField("Enter Amount > " + curr, text: $moneyS)
                .keyboardType(.decimalPad)
        }
    }
}

Also, note, that I have also moved the curr calculation to a variable so that the body code stays small.

Solution 2:[2]

Thanks for the assistance. I like the concise compact code.

Sorry for not being clear about the blah blah blah line. There are other lines of text included in a VStack but just "Enter Amount > " and the currency symbol in the HStack.

Solution 3:[3]

.currency(code: "INR")

You can set country code dynamically.

struct ExchangeRateView: View {

    @State var currencyFromInput:Double = 0.1

    var body: some View {

    TextField("Enter Amount", value: $currencyFromInput, format:  .currency(code: "INR"))

    }

}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Denis
Solution 2 Galen Smith
Solution 3 Arjun Patel