UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Displaying SwiftUi Code on button press

Forums > SwiftUI

I bought the course SwiftUI by examples. As I am pacticing each chapter after finishing the project, I had an idea and want to know if it is feasible. If I change the text font, size or so on, it gets updated on screen. I want to add a button "show code" which prints the code as text. I don't want to repeat the code to execute and to print as it is cumbersome and if I foget keeping both in synch, I might have a problem. Example:

Following code shows the image. I want to add a button beneath the image, which when toggled shows the following code.

Image("rome") .resizable() .frame(height: 200)

Is this something doable?

1      

This is possible but you would need to put the code in seperate Strings. You can't print out the code you have written to execute the app. So in your View you have to declare

let myStringToPrint = "Image(\"rome\").resizable().frame(height: 200)"

and then you can show this String. The \ is needed to escape the " in your String.

1      

How do I execute it? I don't know anyway to run the code using 'myStringToPrint'

Psuedo code looks like following:

Execute myStringToPrint Text(myStringToPrint) on screen on button press

1      

Am not totally sure what your objectives are. SwiftUI has a Mirror struct that is a representation of the substructure and display style of an instance of any type. Buttons are a type, so ipso facto, this probably will tell you the makeup of your button as you change its modifiers.

See -> Mirror in SwiftUI Documentation

But for immediate gratification, create a new project in XCode and paste in this simple view.

import SwiftUI

struct SimpleView: View {

    @State private var incantation = true
    // Change the look and text of a spell.
    var spell:      String { incantation ? "Abracadabra!" : "Mirror, mirror! On the wall..." }
    var spellColor: Color  { Bool.random() ? .red : Bool.random() ? .green : .indigo }

    // Calculate a spell.
    var finalSpell: Text   { Text(spell).font(.title).foregroundColor(spellColor )}

    // Use reflection to see INTO the spell's ingredients.
    var reflection: String { String( reflecting: finalSpell ) }

    var body: some View {
        VStack {
            finalSpell // This is a Text() view with modifiers
            Button("Change Spell") {
                withAnimation { incantation.toggle() }
                print(reflection)  // <- This reflects the definition of the finalSpell object
            }
            .buttonStyle(.borderedProminent)
            .padding(.vertical)
        }
    }
}

When I run this and click the Change Spell button, SwiftUI changes the color and text.

The reflection string reports this change and is printed to the console. Not very pretty, but your homework is to figure out a good way to display the data you need.

My Results

You can see the reflection tells me that my text is "Mirror, mirror! On the wall..."
It also shows the Text view's modifiers are font and color.

For some reason, it cannot decode the font modifier is .title. But it does provide the correct color modifier: .indigo.

SwiftUI.Text(storage: SwiftUI.Text.Storage.verbatim("Mirror, mirror! On the wall..."),             
modifiers: [SwiftUI.Text.Modifier.font(Optional(SwiftUI.Font(provider: SwiftUI.(unknown context at $110487f38).FontBox<SwiftUI.Font.(unknown context at $1104c2d68).TextStyleProvider>))),            
SwiftUI.Text.Modifier.color(Optional(indigo))])

Keep Coding

Please return here and, dare I say it?, please reflect on what you learnt. Please share your reflection code. Let us know how you solved your question.

1      

Addendum:

I changed the finalSpell var above and added a few more modifiers:

    var finalSpell: some View {
        Text(spell)
            .font(.title)
            .foregroundColor(spellColor )
            .frame(height: 70)
            .background(Circle()   // Added background shape
                .fill(.yellow.gradient.opacity(0.5))  // filled with yellow gradient and 50% opacity
                .frame(width: 50, height: 50) // Circle is 50 x 50.
            )
    }

The reflection added more descriptions to reflect the changes. The output is difficult to read, but that could be solved with some clever parsing. (Your job!)

You can find opacity, frame, shape and other modifiers in this.

SwiftUI.ModifiedContent<SwiftUI.ModifiedContent<SwiftUI.Text, SwiftUI._FrameLayout>,
SwiftUI._BackgroundModifier<SwiftUI.ModifiedContent<SwiftUI._ShapeView<SwiftUI.Circle,
SwiftUI._OpacityShapeStyle<SwiftUI.AnyGradient>>,
SwiftUI._FrameLayout>>>(content: SwiftUI.ModifiedContent<SwiftUI.Text,
SwiftUI._FrameLayout>(content: SwiftUI.Text(storage: SwiftUI.Text.Storage.verbatim("Abracadabra!"),
modifiers: [SwiftUI.Text.Modifier.font(Optional(SwiftUI.Font(provider: SwiftUI.(unknown context at $1063d7f38).FontBox<SwiftUI.Font.(unknown context at $106412d68).TextStyleProvider>))), SwiftUI.Text.Modifier.color(Optional(red))]),
modifier: SwiftUI._FrameLayout(width: nil, height: Optional(70.0),
alignment: SwiftUI.Alignment(horizontal: SwiftUI.HorizontalAlignment(key: SwiftUI.AlignmentKey(bits: 2)),
vertical: SwiftUI.VerticalAlignment(key: SwiftUI.AlignmentKey(bits: 5))))),
modifier: SwiftUI._BackgroundModifier<SwiftUI.ModifiedContent<SwiftUI._ShapeView<SwiftUI.Circle,
SwiftUI._OpacityShapeStyle<SwiftUI.AnyGradient>>,
SwiftUI._FrameLayout>>(background: SwiftUI.ModifiedContent<SwiftUI._ShapeView<SwiftUI.Circle,
SwiftUI._OpacityShapeStyle<SwiftUI.AnyGradient>>,
SwiftUI._FrameLayout>(content: SwiftUI._ShapeView<SwiftUI.Circle,
SwiftUI._OpacityShapeStyle<SwiftUI.AnyGradient>>(shape: SwiftUI.Circle(),
style: SwiftUI._OpacityShapeStyle<SwiftUI.AnyGradient>
(style: SwiftUI.AnyGradient(provider: SwiftUI.(unknown context at $10649f748).GradientBox<SwiftUI, opacity: 0.5),
fillStyle: SwiftUI.FillStyle(isEOFilled: false, isAntialiased: true)), modifier: SwiftUI._FrameLayout(width: Optional(50.0), height: Optional(50.0), alignment: SwiftUI.Alignment(horizontal:
SwiftUI.HorizontalAlignment(key: SwiftUI.AlignmentKey(bits: 2)),
vertical: SwiftUI.VerticalAlignment(key: SwiftUI.AlignmentKey(bits: 5))))),
alignment: SwiftUI.Alignment(horizontal: SwiftUI.HorizontalAlignment(key: SwiftUI.AlignmentKey(bits: 2)),
vertical: SwiftUI.VerticalAlignment(key: SwiftUI.AlignmentKey(bits: 5)))))

Good luck!

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.