2017-02-17 105 views
0

我的應用程序分爲2個故事板:一個字符選擇和一個主應用程序。當用戶選擇一個字符時,應用程序會繼續到主應用程序,並且該故事板的所有視圖現在都應該與用戶選擇的字符相關聯。故事板視圖控制器之間共享變量?

我想找出共享一個字符串的最佳方式,該字符串將在所有主應用程序故事板視圖之間具有所選字符的信息。現在,我使用UserDefaults只設置一個全局變量:

func loadMainApp(sender: UITapGestureRecognizer) { 
    let currentCharcter = allCharacters[(sender.view?.tag)!] 
    let defaults: UserDefaults = UserDefaults.standard 
    defaults.setValue(currentCharacter, forKey: "CurrentCharacter") 
    performSegue(withIdentifier: "MainAppSegue", sender: self)  
} 

從那裏在主應用程序情節串連圖板中的所有視圖控制器可以從UserDefaults獲取字符串。

這是做這種事情的最好方法還是有更好的方法?

回答

0

更好的方法是將角色傳遞給您繼續使用的viewController,最簡單的方法是使用prepare(for segue。如果你改變你的performSegue電話說performSegue(withIdentifier: "MainAppSegue", sender: sender)通過發件人上,你將能夠訪問在prepare(for這樣的:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    //Safely check to make sure this is the correct segue by unwrapping the sender and checking the segue identifier 
    if let tapGesture = sender as? UITapGestureRecognizer, let tapGestureView = sender.view, let mainViewController = segue.destination as? MainViewController, segue.identifier == "MainAppSegue" { 

     //Get a reference to the character that was selected 
     let currentCharacter = allCharacters[tapGestureView.tag] 

     //Pass the character to the new viewController 
     mainViewController.character = currentCharacter 
    } 
} 

我做你正在執行的SEGUE到了的viewController的名字一對夫婦的假設,並假定它有一個名爲character的變量,你可以在其中發送你的角色。你的新viewController現在有一個對角色的引用。

0

如果我很瞭解你。我個人使用Singeltons實現視圖之間的全局變量而不是UserDefaults

class SomeClass{ 
static let sharedInstance = SomeClass() 
var someString = "This String is same from any class" 
} 

Usage inside of some function : 
SomeClass.sharedInstance.someString = "Changing Global String" 
相關問題