Text() on button click in SwiftUI

In this tutorial, I will show you how to show Text on button click in SwiftUI with a simple code.

I am making this tutorial because we can not directly write Text()in Button function. So I come up with the idea to use Text() on button click.

Steps:

  • Create a @State variable with String type. ( I am creating @State variable so that I can modify it later on button click)
    We will be able to change or modify the value from anywhere inside the struct.
  • Then I am creating a button like this:
    Button("Press me") {
                       self.name = "Hello text"
                       
                   }
  • Now my aim is to show some text with Text() function.

Take a look at how I did this:

import SwiftUI

struct ContentView: View {
    @State var myText: String = ""
       var body: some View {
           
               Button("Press me") {
                   self.myString = "Welcome to codespeedy!"
                   
               }
            
           Text(myString)
           }
       }

You can write Text(name)outside the Button. If you put it inside Button(){  This area } it won’t work.

We have changed the value of our string variable myText to “Welcome to codespeedy!”.

So whenever I will click on the button named “Press me” it will show the text  Welcome to codespeedy!.

Take a look at how it will look:

Text() on button click in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *