Create a button

Hello everyone.
I would like to create a button in SwiftUI, which initially will display some text and with the click of the user will transform to a number (like initially the button displays "click me to add a number" and when I click on it'll immediately displays number "1" ). Can anyone help me with how to do this? Thanks

Answered by Claude31 in 699825022

Use a state var:

struct NewView: View {

    @State var value = 0

    func changeValue() {
        value += 1 
    }

    var body: some View {

        Text("Hello, World! ")
        Button(action: changeValue) {
            Text(value == 0 ? "click me to add a number" : String(value))
        }
    }
}
Accepted Answer

Use a state var:

struct NewView: View {

    @State var value = 0

    func changeValue() {
        value += 1 
    }

    var body: some View {

        Text("Hello, World! ")
        Button(action: changeValue) {
            Text(value == 0 ? "click me to add a number" : String(value))
        }
    }
}

Thank you very much! Just for curiosity can you explain me the last line you've written, please: Text(value == 0 ? "Some text" : String(value)) ?

Text(value == 0 ? "Some text" : String(value))

When you start, value is 0. And you want to display "click me to add a number"

As soon as you have tapped, value is incremented, and is no more 0. And then you want to display this value.

The above code, using ternary operator, just do this. It is equivalent (functionally) to

var text = ""
if value == 0 {
  text = "click me to add a number"
} else {
  text = String(value)
}
Text(text)

Ok, now is clearer thank you very much!

Create a button
 
 
Q