问题描述
我正在尝试将多个对象从我的初始视图控制器发送到我的 Username VC
.这是我的控制器的 segue 代码:当我添加代码以发送第二个对象 termreport
时,问题就出现了.如果我删除 termsM
和作业,它会像往常一样发送学生,但我还需要发送 termReport
对象.我该如何解决这个问题?
I am trying to send multiple objects from my initial view controller to my Username VC
. Here is the segue code from my controllers: The issue comes when I add in the code to send the second object, termreport
. If I delete the termsM
and the assignment, it send the students as usually, but I also need to send the termReport
object. How would I fix this?
视图控制器:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let students = sender as AnyObject as? [Student]
else { return }
guard let termsM = sender as AnyObject as? [TermReport] //How would I send both objects?
else { return }
if let secondVC = segue.destination as? UsernameVC {
secondVC.students = students
secondVC.userWebView = webView
secondVC.terms = termsM // not sending
}
let gradeResponse = try Parser(innerHTML)
self.performSegue(withIdentifier: "ShowStudents", sender: gradeResponse.students)
self.performSegue(withIdentifier: "ShowStudents", sender: gradeResponse.termReports) //how would I send both variables?
用户名VC:
var terms: [TermReport]!
override func viewDidLoad() {
print("TERM \(terms[0].grades[3])")//returns found nil optional ERROR
}
推荐答案
您必须使用 segue 将要发送到另一个 ViewController
的所有变量包含到单个对象中(可以是一个集合).您可以创建一个具有 [Student]
和 [TermReport]
类型属性的自定义类/结构,或者将它们放入本机集合(元组或字典)中.
You have to include all of the variables you want to send to another ViewController
using a segue into a single object (which can be a collection as well). You either create a custom class/struct that has properties with type [Student]
and [TermReport]
or put these into a native collection (Tuple or Dictionary).
创建自定义结构:
struct TermData {
var students = [Student]()
var termReports = [TermReport]()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let segueData = sender as? TermData
else { return }
if let secondVC = segue.destination as? UsernameVC {
secondVC.students = segueData.students
secondVC.userWebView = webView
secondVC.terms = segueData.termReports
}
}
let gradeResponse = try Parser(innerHTML)
let termData = TermData(students: gradeResponse.students, termReports: gradeResponse.termReports)
self.performSegue(withIdentifier: "ShowStudents", sender: termData)
这篇关于Swift 将多个对象发送到视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!