Div
Div

Reputation: 1603

How to alter a View in SwiftUI

How can I modify a View after using it? E.G:

var body: some View {
    Button (action: {
        // Code to move button's position. self.offset(x:y:) doesn't work, Xcode says 'result of call to offset is unused'
    }) {
        Text("How to I alter the colour of this text?") // Change colour somewhere else in my script
            .background(Color.black)

    }
        .frame(alignment: .leading)

}

I need to modify a View after it has been instantiated. Because everything is a View, from the .frame to the .background, shouldn't I need to reference/delete/modify/add them to the stack?

Upvotes: 1

Views: 3556

Answers (2)

Matteo Pacini
Matteo Pacini

Reputation: 22856

A change of color is a change of state.

You can use the property wrapper @State, which is part of SwiftUI.

More about this in the excellent WWDC 2019 talk:

Introducing SwiftUI: Building Your First App

struct ContentView: View {

    @State var someState: Bool = true

    var body: some View {
        Button (action: {
            // The state is toggled, and a redraw is triggered
            self.someState.toggle()
        }) {
        Text("How do I alter the colour of this text?")
            // Set color according to the state
            .foregroundColor(someState ? Color.black : Color.pink)
        }
        .frame(alignment: .leading)
    }

}

When a change of @State occurs, the view body is redrawn.

Upvotes: 7

Fogmeister
Fogmeister

Reputation: 77661

SwiftUI requires a complete change of thought patterns compared to using UIKit.

The "view" you are referring to is not actually a view. It is a set of instructions of how to render something onto the screen. So you can't access it with a reference etc...

To change the way a view looks you can use modifiers on it as you are creating it.

For instance...

Button(action: {}) {
    Text("Hello world!")
        .foregroundColor(.yellow)
}

It really depends what you want to do with it.

Having said that. It is clear that you haven't spent any time watching the WWDC videos or going through the SwiftUI tutorials.

I would recommend doing these before you go any further.

https://developer.apple.com/tutorials/swiftui/

Upvotes: 3

Related Questions