从包含多个条目的不同视图控制器调用struct(swift4)

时间:2017-10-15 18:12:47

标签: ios struct uiviewcontroller call swift4

我正在尝试从twoVIEWCONTROLLER中调用struct person中的let name语句。我以为我可以从另一个视图控制器调用一个结构条目,但我不确定。我遇到的主要问题是结构只能进入一次。现在的代码可以转让购买仅一次进入的结构购买。我如何获得结构存储多个条目。

的viewController

        import UIKit
class ViewController: UIViewController {
@IBOutlet var a: UITextField!
    @IBOutlet var label: UILabel!
    var contacts = [Person]()

    @IBAction func save(_ sender: Any) {
        let newPerson = Person(name: a.text!)
        contacts.append(newPerson)
        contacts.sort { $0.name < $1.name }
        self.selectedPerson = newPerson
    }

    var selectedPerson:Person?
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? twoViewController {
            if self.selectedPerson != nil {
                vc.person = selectedPerson
            }}}
        }
                            struct Person: CustomStringConvertible {
                                let name: String

                                var description: String {
                                    return name
                                }}

twoVIEWCONTROLLER

import  UIKit
class twoViewController: UIViewController {
    @IBOutlet var l: UILabel!

    var person:Person?
    override func viewDidLoad() {
        super.viewDidLoad()
        if let p = self.person {
            l.text = p.name
        }}}

1 个答案:

答案 0 :(得分:0)

struct Contacts {
    var all = [Person]()
}

struct Person: CustomStringConvertible {
    let name: String

    var description: String {
        return name
    }
}

class ViewController: UIViewController {
    @IBOutlet var a: UITextField!
    @IBOutlet var label: UILabel!
    var contacts = Contacts()

    @IBAction func save(_ sender: Any) {
        let newPerson = Person(name: a.text!)
        contacts.all.append(newPerson)
        contacts.all.sort { $0.name < $1.name }
        self.selectedPerson = newPerson
    }

    var selectedPerson:Person?
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? twoViewController {
            if self.selectedPerson != nil {
                vc.person = selectedPerson
                vc.contacts = contacts
            }
        }
    }
}

第二

class twoViewController: UIViewController {
    @IBOutlet var l: UILabel!

    var contacts: Contacts?
    var person:Person?
    override func viewDidLoad() {
        super.viewDidLoad()
        if let p = self.person {
            l.text = p.name
        }
    }
}