静态@state 字符串字段
Static @state string field
我有文本字段,我需要使用静态函数更改文本字段中的文本。
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.: 对不起我的英文)))
我不明白你为什么坚持使用静态函数来改变你的文本...
也许我错了,但试试这个:
struct MainScreen: View {
@State var myText: String = "Default Text"
var body: some View {
Text("\(myText)")
}
func changeText(newText: String) {
self.myText = "New Text Now"
}
}
它对我有用,希望对你也有帮助。
与需要这样做的原因无关,请在下面找到实现请求行为的可能方法。测试并适用于 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
}
}
我有文本字段,我需要使用静态函数更改文本字段中的文本。
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"
?
P.S.: 对不起我的英文)))
我不明白你为什么坚持使用静态函数来改变你的文本...
也许我错了,但试试这个:
struct MainScreen: View {
@State var myText: String = "Default Text"
var body: some View {
Text("\(myText)")
}
func changeText(newText: String) {
self.myText = "New Text Now"
}
}
它对我有用,希望对你也有帮助。
与需要这样做的原因无关,请在下面找到实现请求行为的可能方法。测试并适用于 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
}
}