2017-08-03 59 views
0

我是新來的swift如此裸露與我。如何:用戶從其他ViewController中的數組添加/刪除?

我有一個空的userArrayviewController1將使用字符串。 在彈出的對話框中,viewController2,我希望用戶可以添加或刪除此userArray

我會使用textField爲用戶添加他們的字符串,但什麼是一個簡單的方法讓用戶看到數組的內容並從中刪除?

如何在viewControllers之間傳遞此數據,同時確保它被保存,並且您推薦我使用哪些數據從陣列中刪除?

預先感謝您!

回答

1

假設你有一個從viewController1viewController2一個SEGUE,你可以使用segue.destination並設置爲任何你想要的segue.destination.userArray財產。

如果你沒有segue,你試圖做的是在視圖控制器之間共享一個模型,你可以做的一件事就是創建另一個具有靜態屬性userArray的類,並以此方式訪問它。

至於陣列移除,請參見https://developer.apple.com/documentation/swift/array/1641390-remove

+0

很好的答案謝謝! 不幸的是我現在遇到了另一個問題。當segue執行並且我到達我想要的ViewController時,導航欄中的「後退」按鈕將我放回ViewController,我只是從該控件繼續前進,而不是返回到它應該返回的ViewController。你知道如何解決這個問題嗎? – Alvarsson

+0

@Alvarsson你能澄清一下嗎?我從你的描述中瞭解到,這是預期的行爲。祝你好運:) –

+0

當然!所以我實際上有3個ViewControllers,全部使用導航控制器。所以我想要執行的是從VC3到VC2。 但是,當我在segue後直接返回到VC2時,導航欄上的「後退」按鈕(在VC2中)將我指回VC3而不是主VC1。 VC正在viewcontroller。如果我忘了提問某事就問。 謝謝@MihirThanekar – Alvarsson

-1

在您的ViewController類之外寫入您的數組。然後你可以從其他ViewControllers訪問它。

例子:

//ViewController1.swift 


import UIKit 

var userArray = [String]() 

class ViewController1: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 



//ViewController2.swift 


import UIKit 

class ViewController2: UIViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     userArray.append("A") 
     userArray.append("B") 
     userArray.remove(at: 0) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

} 
+0

否;這是一個壞主意。大多數情況下,如果要添加一個全局變量(即不在類或結構的範圍內),還有更好的方法。在這種情況下,@ Mihir的答案的第一部分更好。 – NRitH

相關問題