swiftui 将变量传递到另一个视图 [英] swiftui passing variable into antoher view
问题描述
嘿,下面你可以找到我的源代码.我想做的是:
Hey below you find my source code. What i wanna do is:
提取 Json 后,我希望它可以在其他视图中访问...请帮帮我...
After the Json is extracted I want that it will be accessable in a other view... Please help me...
我的意思是提取的值:"\n (users.Name)"
I Mean the extracted Value: "\n (users.Name)"
所以我只想将响应数据放入另一个视图中...
So I want simply the response data into a other view...
struct User: Codable {
let Name: String
}
let url = URL(string: "http://192.168.178.26/iso/loginserv.php")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString = "user=\(self.user)&pass=\(self.pass)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in
if let error = error {
print("Error took place \(error)")
return
}
guard let data = data else {return}
do{
let users = try JSONDecoder().decode(User.self, from: data)
print("Response data Name: \n \(users.Name)")
if !(data.isEmpty) {
self.signedIn = true
}
}catch let jsonErr{
print(jsonErr)
}
}
task.resume()
推荐答案
你可以做的是使用单例设计模式.
What you could do is use Singleton design pattern.
基本上,您创建一个仅实例化一次的类,具有全局静态属性.该属性将用于将信息从一个视图传递到另一个视图.
Basically you create a class that is instanced a single time only, with a global static property. That property will be used to pass info from one view to another.
因此,首先创建一个 Singleton 类(作为一个简单的 Swift 文件)并定义一个静态实例,如下所示:
So, first create a Singleton class (as a simple Swift file) and define a static instance, like this:
class Singleton {
static let instance = Singleton()
private init() {
}
}
现在,创建并初始化要在视图之间共享的变量,例如字符串 name
:
Now, create and initialize the variable you want to share between views, for example the string name
:
class Singleton {
static let instance = Singleton()
private init() {
}
var name = ""
}
现在,在您的代码中,将 users.Name
属性赋予它:
Now, in your code, attribute users.Name
to it:
do{
let users = try JSONDecoder().decode(User.self, from: data)
print("Response data Name: \n \(users.Name)")
Singleton.instance.name = users.Name
if !(data.isEmpty) {
self.signedIn = true
}
}catch let jsonErr{
print(jsonErr)
}
现在,要在另一个视图中访问此信息,只需使用 Singleton.instance.name
.
Now, to access this info in another view, just use Singleton.instance.name
.
这篇关于swiftui 将变量传递到另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!