【问题标题】:Static @state string field静态@state 字符串字段
【发布时间】:2020-03-12 08:32:26
【问题描述】:

我有文本字段,我需要使用静态函数更改文本字段中的文本。

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
   }
}

我该怎么做?或者如果我要使用@State var mytext = "TEXT",我怎样才能在静态函数中获取 MainScreen.self?

P.S.:对不起我的英语)))

【问题讨论】:

  • 您希望通过将@State 变量设为静态来实现什么目的?

标签: swift class swiftui field


【解决方案1】:

与为什么需要这样做的原因无关,请在下面找到实现请求行为的可能方法。经过测试并与 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
    }
}

【讨论】:

    【解决方案2】:

    我不明白你为什么坚持使用静态函数来改变你的文字...

    也许我错了,但试试这个:

    struct MainScreen: View {
    @State var myText: String = "Default Text"
    var body: some View {
        Text("\(myText)")
    }
    
    func changeText(newText: String) {
        self.myText = "New Text Now"
    }
    }
    

    它对我有用,我希望它也能帮助你。

    【讨论】:

    • 很明显。我需要 MainScreen 对象才能使用此功能!如何在静态上下文中获取它?
    • 我不确定你在说什么。也许您可以在上面发布您的代码。检查这个网站,可能有一些你需要的 swiftUI 资源。 hackingwithswift.com/read/0/18/static-properties-and-methods
    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多