我希望能够在vc2中调用var person,以便在vc2中的标签上显示l.text =。多数民众赞成是否有可能。
VC
import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
var persons:[Person] = [Person]()
@IBAction func save(_ sender: Any) {
let judo = Person.init(name: a.text ?? "", phone: Int(c.text ?? "") ?? 0)
self.persons.append(judo)
}
struct Person : CustomStringConvertible {
var name: String
var phone: Int
static var myStruct = [String]();
var description: String {
return "\(name),\(phone)"
}}}
VC2
import UIKit
class twoViewController: UIViewController {
@IBOutlet var l: UILabel!
override func viewDidLoad() {
l.text =
}}
答案 0 :(得分:0)
有两种方法可以解决这个问题。
我建议的是:
1:在课程之外的某处创建协议:
protocol ViewControllerDelegate: class {
func passPerson(_ Person)
}
2:在VC1中创建一个委托,如下所示:
import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
var delegate: ViewControllerDelegate?
var persons:[Person] = [Person]()
@IBAction func save(_ sender: Any) {
let judo = Person.init(name: a.text ?? "", phone: Int(c.text ?? "") ?? 0)
self.persons.append(judo)
}
}
3:像这样实施prepareForSegue:
方法:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let secondVC = segue.destination as? VC2 {
delegate = segue.destination
delegate.passPerson(persons[3])
}
}
4:在第二个VC中:
class SecondVC: UIViewController, ViewControllerDelegate {
...
func passPerson(_ Person) {
//do whatever you want
}
实现相同目标的另一种方法是让persons
数组成为全局变量,但我不推荐它,因为稍后当您的应用变得更复杂时,它可能会变得非常混乱。< / p>
编辑:正如@LeoDabus建议的那样,您也可以在VC2中创建一个变量,当需要导航到VC2时,您可以设置该属性。