Static @state string field

Viewed 224

I have textfield, and I need to change text in textfield using static function.

import SwiftUI

struct MainScreen: View
{
   @State static var mytext = "TEXT"
   var body: some View
   {
       Text(MainScreen.mytext)
   }

   public static func showtext(newtext: String)
   {
       MainScreen.mytext = newtext
   }
}

How can I do it? Or how can I get MainScreen.self in static function, if I will use @State var mytext = "TEXT"?

P.S.: sorry for my English)))

2 Answers

Irrelative to the reason of why this is needed, please find below possible approach to achieve requested behavior. Tested & works with Xcode 11.2 / iOS 13.2

import Combine

struct MainScreen: View
{
    // shared publisher
    static let publisher = PassthroughSubject<String, Never>()

    @State private var mytext = "TEXT" // << !! can be only per-view, make always private
    var body: some View
    {
        VStack {
            Text(mytext)
                .onReceive(MainScreen.publisher) { value in // listen for shared publisher
                    self.mytext = value // update with new value
            }

            // this button is just for demo
            Button("Show") { MainScreen.showtext(newtext: "Updated Text!") }
        }
    }

    public static func showtext(newtext: String)
    {
        MainScreen.publisher.send(newtext) // post via shared publisher
    }
}

I don't understand that why you insist using static function to change your text...

Maybe I'm wrong, but try this:

struct MainScreen: View {
@State var myText: String = "Default Text"
var body: some View {
    Text("\(myText)")
}

func changeText(newText: String) {
    self.myText = "New Text Now"
}
}

It can work to me and I hope it will help you, too.

Related