2017-10-15 139 views
0

我想調用twoVIEWCONTROLLER結構人內部的名稱聲明。我以爲我可以從另一個視圖控制器調用結構條目,但我不確定。我所面臨的主要問題是結構只能進入一次。現在的代碼是可以轉讓結構購買只有一個入口被保存。我如何獲得結構來存儲多個條目。從不同的視圖控制器調用結構保存多個條目(swift4)

的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 
     }}} 
+0

您需要訪問的人的實例來訪問該實例的'name'屬性。 – dasdom

+0

你沒有說如果'ViewController'呈現'twoViewController'或都是完全獨立的... – Ladislav

+0

@Ladislav我試圖做到這兩個viewcontrollers行事互相獨立。 –

回答

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 
     } 
    } 
} 
+0

這有效,但問題是它一次只能保存1個條目。每次保存時,打印文件都被刪除。 –

相關問題